Part Number Hot Search : 
ACA2786 27HF6 M2326 00LVE TC7211AM UM810AEP 60601B HCC4052B
Product Description
Full Text Search
 

To Download ATMEGA16HVB-8X3 Datasheet File

  If you can't view the Datasheet, Please click here to try to view without PDF Reader .  
 
 


  Datasheet File OCR Text:
 Features
* High Performance, Low Power AVR(R) 8-bit Microcontroller * Advanced RISC Architecture
- 124 Powerful Instructions - Most Single Clock Cycle Execution - 32 x 8 General Purpose Working Registers - Fully Static Operation - Up to 8 MIPS Throughput at 8 MHz High Endurance Non-volatile Memory Segments - 16K/32K Bytes of In-System Self-Programmable Flash (ATmega16HVB/32HVB) - 512/1K Bytes EEPROM - 1K/2K Bytes Internal SRAM - Write/Erase Cycles 10,000 Flash/100,000 EEPROM - Data retention: 20 years at 85C/100 years at 25C(1) - Optional Boot Code Section with Independent Lock Bits In-System Programming by On-chip Boot Program True Read-While-Write Operation - Programming Lock for Software Security Battery Management Features - Two, three or Four Cells in Series - High-current Protection (Charge and Discharge) - Over-current Protection (Charge and Discharge) - Short-circuit Protection (Discharge) - High Voltage Outputs to Drive N-Channel Charge/Discharge FETs - Optional Deep Under Voltage Recovery mode - allowing 0-volt charging without external Precharge FET - Optional High Voltage Open Drain ouput - allowing 0-volt charging with external Precharge FET - Integrated Cell Balancing FETs Peripheral Features - Two configurable 8- or 16-bit Timers with Separate Prescaler, Optional Input Capture (IC), Compare Mode and CTC - SPI - Serial Peripheral Interface - 12-bit Voltage ADC, Six External and One Internal ADC Input - High Resolution Coulomb Counter ADC for Current Measurements - TWI Serial Interface supporting SMBus implementation - Programmable Watchdog Timer Special Microcontroller Features - debugWIRE On-chip Debug System - In-System Programmable via SPI ports - Power-on Reset - On-chip Voltage Regulator with Short-circuit Monitoring Interface - External and Internal Interrupt Sources - Sleep Modes: Idle, ADC Noise Reduction, Power-save, and Power-off Additional Secure Authentication Features available only under NDA Packages - 44-pin TSSOP Operating Voltage: 4 - 25V Maximum Withstand Voltage (High-voltage pins): 35V Temperature Range: -40C to 85C Speed Grade: 1-8 MHz
*
*
8-bit Microcontroller with 16K/32K Bytes In-System Programmable Flash
ATmega16HVB ATmega32HVB Preliminary
*
*
* * * * * *
Note:
1. See "Data Retention" on page 8 for details.
8042A-AVR-07/09
ATmega16HVB/32HVB
1. Pin Configurations
1.1 TSSOP
Figure 1-1. TSSOP - pinout ATmega16HVB/32HVB
NI NNI VREFGND VREF GND VREG PA0(ADC0/SGND/PCINT0) PA1(ADC1/SGND/PCINT1) PA2(PCINT2/T0) PA3(PCINT3/T1) VCLMP10 VFET BATT VCC GND OD NC OC RESET/dw PB0(PCINT4/ICP00) PB1(PCINT5/CKOUT) PB2(PCINT6)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
44 43 42 41 40 39 38 37 36 35 34 33 32 31 30 29 28 27 26 25 24 23
PI PPI NV PV1 PV2 PV3 PV4 PVT VCC GND PC5 PC4(SCL) PC3(INT3/SDA) PC2(INT2) PC1(INT1) PC0(INT0/EXTPROT) PB7(MISO/PCINT11) NC PB6(MOSI/PCINT10) PB5(SCK/PCINT9) PB4(SS/PCINT8) PB3(PCINT7)
1.2
Pin Descriptions
1.2.1
VFET High voltage supply pin. This pin is used as supply for the internal voltage regulator, described in "Voltage Regulator" on page 132.
1.2.2
VCLMP10 Internal 10V clamping of VFET voltage for external decoupling.
1.2.3
VCC Digital supply voltage. Normally connected to VREG.
2
8042A-AVR-07/09
ATmega16HVB/32HVB
1.2.4 VREG Output from the internal Voltage Regulator. Used for external decoupling to ensure stable regulator operation. For details, see "Voltage Regulator" on page 132. 1.2.5 VREF Internal Voltage Reference for external decoupling. For details, see "Voltage Reference and Temperature Sensor" on page 123. 1.2.6 VREFGND Ground for decoupling of Internal Voltage Reference. For details, see "Voltage Reference and Temperature Sensor" on page 123. Do not connect to GND or SGND on PCB. 1.2.7 GND Ground 1.2.8 Port A (PA3..PA0) Port A serves as a low-voltage 4-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). As inputs, Port A pins that are externally pulled low will source current if the pull-up resistors are activated. The Port A pins are tri-stated when a reset condition becomes active, even if the clock is not running. Port A also serves the functions of various special features of the ATmega16HVB/32HVB as listed in "Alternate Functions of Port A" on page 74. 1.2.9 Port B (PB7..PB0) Port B is a low-voltage 8-bit bi-directional I/O port with internal pull-up resistors (selected for each bit). As inputs, Port B pins that are externally pulled low will source current if the pull-up resistors are activated. The Port B pins are tri-stated when a reset condition becomes active, even if the clock is not running. Port B also serves the functions of various special features of the ATmega16HVB/32HVB as listed in "Alternate Functions of Port B" on page 75. 1.2.10 Port C (PC5) Port C (PC5) is a high voltage Open Drain output port. 1.2.11 Port C (PC4..PC0) Port C is a 5-bit high voltage Open Drain bi-directional I/O port. 1.2.12 OC/OD High voltage output to drive Charge/Discharge FET. For details, see "FET Driver" on page 148. 1.2.13 PI/NI Filtered positive/negative input from external current sense resistor, used to by the Coulomb Counter ADC to measure charge/discharge currents flowing in the battery pack. For details, see "Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC" on page 108.
3
8042A-AVR-07/09
ATmega16HVB/32HVB
1.2.14 PPI/NNI Unfiltered positive/negative input from external current sense resistor, used by the battery protection circuit, for over-current and short-circuit detection. For details, see "Battery Protection" on page 135. 1.2.15 NV/PV1/PV2/PV3/PV4 NV, PV1, PV2, PV3, and PV4 are the inputs for battery cells 1, 2, 3 and 4, used by the Voltage ADC to measure each cell voltage. For details, see "Voltage ADC - 7-channel General Purpose 12-bit Sigma-Delta ADC" on page 117. 1.2.16 PVT Defines the source voltage level for the Charge FET driver. For details, see "FET Driver" on page 148. 1.2.17 BATT Input for detecting when a charger is connected. Defines the source voltage level for the Discharge FET driver. For details, see "FET Driver" on page 148. 1.2.18 RESET/dw Reset input. A low level on this pin for longer than the minimum pulse length will generate a reset, even if the clock is not running. The minimum pulse length is given in Table 11 on page 38. Shorter pulses are not guaranteed to generate a reset. This pin is also used as debugWIRE communication pin.
4
8042A-AVR-07/09
ATmega16HVB/32HVB
2. Overview
The ATmega16HVB/32HVB is a monitoring and protection circuit for 3 and 4-cell Li-ion applications with focus on highest safety including safe authentication, low cost and high utilization of the cell energy. The device contains secure authentication features as well as autonomous battery protection during charging and discharging. The External Protection Input can be used to implement other battery protection mechanisms using external components, e.g. protection against chargers with too high charge voltage can be easily implemented with a few low cost passive components. The feature set makes the ATmega16HVB/32HVB a key component in any system focusing on high security, battery protection, high system utilization and low cost. Figure 2-1. Block Diagram
PB7..0
PC5..0
PB0 Oscillator Circuits / Clock Generation Oscillator Sampling Interface SPI VCC Watchdog Timer Flash SRAM 8/16-bit T/C1 Voltage ADC TWI 8/16-bit T/C0 FET Control
OC OD
PORTB (8)
PORTC (6)
Watchdog Oscillator
Current Protection Cell Balancing
PPI NNI PV4 PV3 PV2 PV1 NV
RESET/dW
Power Supervision POR & RESET
Program Logic
debugWIRE
VPTAT CPU EEPROM Voltage Reference VREF VREFGND PI NI
GND BATT Charger Detect
Security Module DATA BUS
Coulomb Counter ADC
VFET VREG
Voltage Regulator
Voltage Regulator Monitor Interface
PORTA (4) PA1..0
PA3..0
ATmega16HVB/32HVB provides the necessary redundancy on-chip to make sure that the battery is protected in critical failure modes. The chip is specifically designed to provide safety for the battery cells in case of pin shorting, loss of power (either caused by battery pack short or
5
8042A-AVR-07/09
ATmega16HVB/32HVB
VCC short), illegal charger connection or software runaway. This makes ATmega16HVB/32HVB the ideal 1-chip solution for applications with focus on high safety. The ATmega16HVB/32HVB features an integrated voltage regulator that operates at a wide range of input voltages, 4 - 25 volts. This voltage is regulated to a constant supply voltage of nominally 3.3 volts for the integrated logic and analog functions. The regulator capabilities, combined with an extremely low power consumption in the power saving modes, greatly enhances the cell energy utilization compared to existing solutions. The chip utilizes Atmel's patented Deep Under-voltage Recovery (DUVR) mode that supports pre-charging of deeply discharged battery cells without using a separate Pre-charge FET. Optionally, Pre-charge FETs are supported for integration into many existing battery charging schemes. The battery protection monitors the charge and discharge current to detect illegal conditions and protect the battery from these when required. A 12-bit Voltage ADC allows software to monitor each cell voltage individually with high accuracy. The ADC also provides one internal input channel to measure on-chip temperature and two input channels intended for external thermistors. An 18-bit ADC optimized for Coulomb Counting accumulates charge and discharge currents and reports accumulated current with high resolution and accuracy. It can also be used to provide instantaneous current measurements with 13 bit resolution. Integrated Cell Balancing FETs allow cell balancing algorithms to be implemented in software. The MCU provides the following features: 16K/32K bytes of In-System Programmable Flash with Read-While-Write capabilities, 512/1K bytes EEPROM, 1K/2K bytes SRAM. 32 general purpose working registers, 12 general purpose I/O lines, 5 general purpose high voltage open drain I/O lines, one general purpose super high voltage open drain output, debugWIRE for On-chip debugging and SPI for In-system Programming, a SM-Bus compliant TWI module, two flexible Timer/Counters with Input Capture and compare modes. Internal and external interrupts, a 12-bit Sigma Delta ADC for voltage and temperature measurements, a high resolution Sigma Delta ADC for Coulomb Counting and instantaneous current measurements, integrated cell balancing FETs, Additional Secure Authentication Features, an autonomous Battery Protection module, a programmable Watchdog Timer with internal Oscillator, and software selectable power saving modes. The AVR core combines a rich instruction set with 32 general purpose working registers. All the 32 registers are directly connected to the Arithmetic Logic Unit (ALU), allowing two independent registers to be accessed in one single instruction executed in one clock cycle. The resulting architecture is more code efficient while achieving throughputs up to ten times faster than conventional CISC microcontrollers. The device is manufactured using Atmel's high voltage high density non-volatile memory technology. The On-chip ISP Flash allows the program memory to be reprogrammed In-System, through an SPI serial interface, by a conventional non-volatile memory programmer or by an Onchip Boot program running on the AVR core. The Boot program can use any interface to download the application program in the Application Flash memory. Software in the Boot Flash section will continue to run while the Application Flash section is updated, providing true ReadWhile-Write operation. By combining an 8-bit RISC CPU with In-System Self-ProgrammableFlash and highly accurate analog front-end in a monolithic chip. The Atmel ATmega16HVB/32HVB is a powerful microcontroller that provides a highly flexible and cost effective solution. It is part of the AVR Battery Management family that provides secure
6
8042A-AVR-07/09
ATmega16HVB/32HVB
authentication, highly accurate monitoring and autonomous protection for Lithium-ion battery cells. The ATmega16HVB/32HVB AVR is supported with a full suite of program and system development tools including: C Compilers, Macro Assemblers, Program Debugger/Simulators, and Onchip Debugger.
2.1
Comparison Between ATmega16HVB and ATmega32HVB
The ATmega16HVB and ATmega32HVB differ only in memory size for Flash, EEPROM and internal SRAM. Table 2-1 summarizes the different configuration for the two devices. Table 2-1. Configuration summary
Device ATmega16HVB ATmega32HVB Flash 16K 32K EEPROM 512 1K SRAM 1K 2K
7
8042A-AVR-07/09
ATmega16HVB/32HVB
3. Disclaimer
All parameters contained in this datasheet are preliminary and based on characterization of ATmega16/32HVB.
4. Resources
A comprehensive set of development tools, application notes and datasheets are available for download on http://www.atmel.com/avr.n1
Note: 1.
5. About Code Examples
This documentation contains simple code examples that briefly show how to use various parts of the device. These code examples assume that the part specific header file is included before compilation. Be aware that not all C compiler vendors include bit definitions in the header files and interrupt handling in C is compiler dependent. Please confirm with the C compiler documentation for more details. For I/O registers located in extended I/O map, "IN", "OUT", "SBIS", "SBIC", "CBI", and "SBI" instructions must be replaced with instructions that allow access to extended I/O. Typically "LDS" and "STS" combined with "SBRS", "SBRC", "SBR", and "CBR".
6. Data Retention
Reliability Qualification results show that the projected data retention failure rate is much less than 1 PPM over 20 years at 85C or 100 years at 25C.
8
8042A-AVR-07/09
ATmega16HVB/32HVB
7. AVR CPU Core
7.1 Overview
This section discusses the AVR core architecture in general. The main function of the CPU core is to ensure correct program execution. The CPU must therefore be able to access memories, perform calculations, control peripherals, and handle interrupts. Figure 7-1. Block Diagram of the AVR Architecture
Data Bus 8-bit
Flash Program Memory
Program Counter
Status and Control
Instruction Register
32 x 8 General Purpose Registrers
Interrupt Unit Watchdog Timer
Indirect Addressing
Instruction Decoder
Direct Addressing
ALU I/O Module1
Control Lines
I/O Module 2
Data SRAM
I/O Module n
EEPROM
I/O Lines
In order to maximize performance and parallelism, the AVR uses a Harvard architecture - with separate memories and buses for program and data. Instructions in the program memory are executed with a single level pipelining. While one instruction is being executed, the next instruction is pre-fetched from the program memory. This concept enables instructions to be executed in every clock cycle. The program memory is In-System Reprogrammable Flash memory. The fast-access Register File contains 32 x 8-bit general purpose working registers with a single clock cycle access time. This allows single-cycle Arithmetic Logic Unit (ALU) operation. In a typ-
9
8042A-AVR-07/09
ATmega16HVB/32HVB
ical ALU operation, two operands are output from the Register File, the operation is executed, and the result is stored back in the Register File - in one clock cycle. Six of the 32 registers can be used as three 16-bit indirect address register pointers for Data Space addressing - enabling efficient address calculations. One of the these address pointers can also be used as an address pointer for look up tables in Flash program memory. These added function registers are the 16-bit X-, Y-, and Z-register, described later in this section. The ALU supports arithmetic and logic operations between registers or between a constant and a register. Single register operations can also be executed in the ALU. After an arithmetic operation, the Status Register is updated to reflect information about the result of the operation. Program flow is provided by conditional and unconditional jump and call instructions, able to directly address the whole address space. Most AVR instructions have a single 16-bit word format. Every program memory address contains a 16- or 32-bit instruction. During interrupts and subroutine calls, the return address Program Counter (PC) is stored on the Stack. The Stack is effectively allocated in the general data SRAM, and consequently the Stack size is only limited by the total SRAM size and the usage of the SRAM. All user programs must initialize the SP in the Reset routine (before subroutines or interrupts are executed). The Stack Pointer (SP) is read/write accessible in the I/O space. The data SRAM can easily be accessed through the five different addressing modes supported in the AVR architecture. The memory spaces in the AVR architecture are all linear and regular memory maps. A flexible interrupt module has its control registers in the I/O space with an additional Global Interrupt Enable bit in the Status Register. All interrupts have a separate Interrupt Vector in the Interrupt Vector table. The interrupts have priority in accordance with their Interrupt Vector position. The lower the Interrupt Vector address, the higher the priority. The I/O memory space contains 64 addresses for CPU peripheral functions as Control Registers, SPI, and other I/O functions. The I/O Memory can be accessed directly, or as the Data Space locations following those of the Register File, 0x20 - 0x5F. In addition, the ATmega16HVB/32HVB has Extended I/O space from 0x60 - 0xFF in SRAM where only the ST/STS/STD and LD/LDS/LDD instructions can be used.
7.2
ALU - Arithmetic Logic Unit
The high-performance AVR ALU operates in direct connection with all the 32 general purpose working registers. Within a single clock cycle, arithmetic operations between general purpose registers or between a register and an immediate are executed. The ALU operations are divided into three main categories - arithmetic, logical, and bit-functions. Some implementations of the architecture also provide a powerful multiplier supporting both signed/unsigned multiplication and fractional format. See the "Instruction Set" section for a detailed description.
7.3
Status Register
The Status Register contains information about the result of the most recently executed arithmetic instruction. This information can be used for altering program flow in order to perform conditional operations. Note that the Status Register is updated after all ALU operations, as specified in the Instruction Set Reference. This will in many cases remove the need for using the dedicated compare instructions, resulting in faster and more compact code. The Status Register is not automatically stored when entering an interrupt routine and restored when returning from an interrupt. This must be handled by software.
10
8042A-AVR-07/09
ATmega16HVB/32HVB
7.3.1 SREG - AVR Status Register
Bit 0x3F (0x5F) Read/Write Initial Value
7 I R/W 0
6 T R/W 0
5 H R/W 0
4 S R/W 0
3 V R/W 0
2 N R/W 0
1 Z R/W 0
0 C R/W 0 SREG
* Bit 7 - I: Global Interrupt Enable The Global Interrupt Enable bit must be set for the interrupts to be enabled. The individual interrupt enable control is then performed in separate control registers. If the Global Interrupt Enable Register is cleared, none of the interrupts are enabled independent of the individual interrupt enable settings. The I-bit is cleared by hardware after an interrupt has occurred, and is set by the RETI instruction to enable subsequent interrupts. The I-bit can also be set and cleared by the application with the SEI and CLI instructions, as described in the instruction set reference. * Bit 6 - T: Bit Copy Storage The Bit Copy instructions BLD (Bit LoaD) and BST (Bit STore) use the T-bit as source or destination for the operated bit. A bit from a register in the Register File can be copied into T by the BST instruction, and a bit in T can be copied into a bit in a register in the Register File by the BLD instruction. * Bit 5 - H: Half Carry Flag The Half Carry Flag H indicates a Half Carry in some arithmetic operations. Half Carry Is useful in BCD arithmetic. See the "Instruction Set Description" for detailed information. * Bit 4 - S: Sign Bit, S = N V The S-bit is always an exclusive or between the negative flag N and the Two's Complement Overflow Flag V. See the "Instruction Set Description" for detailed information. * Bit 3 - V: Two's Complement Overflow Flag The Two's Complement Overflow Flag V supports two's complement arithmetics. See the "Instruction Set Description" for detailed information. * Bit 2 - N: Negative Flag The Negative Flag N indicates a negative result in an arithmetic or logic operation. See the "Instruction Set Description" for detailed information. * Bit 1 - Z: Zero Flag The Zero Flag Z indicates a zero result in an arithmetic or logic operation. See the "Instruction Set Description" for detailed information. * Bit 0 - C: Carry Flag The Carry Flag C indicates a carry in an arithmetic or logic operation. See the "Instruction Set Description" for detailed information.
11
8042A-AVR-07/09
ATmega16HVB/32HVB
7.4 General Purpose Register File
The Register File is optimized for the AVR Enhanced RISC instruction set. In order to achieve the required performance and flexibility, the following input/output schemes are supported by the Register File: * One 8-bit output operand and one 8-bit result input * Two 8-bit output operands and one 8-bit result input * Two 8-bit output operands and one 16-bit result input * One 16-bit output operand and one 16-bit result input Figure 7-2 shows the structure of the 32 general purpose working registers in the CPU. Figure 7-2. AVR CPU General Purpose Working Registers
7 R0 R1 R2 ... R13 General Purpose Working Registers R14 R15 R16 R17 ... R26 R27 R28 R29 R30 R31 0x1A 0x1B 0x1C 0x1D 0x1E 0x1F X-register Low Byte X-register High Byte Y-register Low Byte Y-register High Byte Z-register Low Byte Z-register High Byte 0x0D 0x0E 0x0F 0x10 0x11 0 Addr. 0x00 0x01 0x02
Most of the instructions operating on the Register File have direct access to all registers, and most of them are single cycle instructions. As shown in Figure 7-2, each register is also assigned a data memory address, mapping them directly into the first 32 locations of the user Data Space. Although not being physically implemented as SRAM locations, this memory organization provides great flexibility in access of the registers, as the X-, Y- and Z-pointer registers can be set to index any register in the file. 7.4.1 The X-register, Y-register, and Z-register The registers R26..R31 have some added functions to their general purpose usage. These registers are 16-bit address pointers for indirect addressing of the data space. The three indirect address registers X, Y, and Z are defined as described in Figure 7-3 on page 13.
12
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 7-3. The X-, Y-, and Z-registers
15 X-register 7 R27 (0x1B) XH 0 7 R26 (0x1A) XL 0 0
15 Y-register 7 R29 (0x1D) 15 Z-register 7 R31 (0x1F)
YH 0 7 R28 (0x1C) ZH 0 7 R30 (0x1E)
YL
0 0
ZL 0
0
In the different addressing modes these address registers have functions as fixed displacement, automatic increment, and automatic decrement (see the instruction set reference for details).
7.5
Stack Pointer
The Stack is mainly used for storing temporary data, for storing local variables and for storing return addresses after interrupts and subroutine calls. The Stack Pointer Register always points to the top of the Stack. Note that the Stack is implemented as growing from higher memory locations to lower memory locations. This implies that a Stack PUSH command decreases the Stack Pointer. The Stack Pointer points to the data SRAM Stack area where the Subroutine and Interrupt Stacks are located. This Stack space in the data SRAM must be defined by the program before any subroutine calls are executed or interrupts are enabled. The Stack Pointer must be set to point above 0x100. The Stack Pointer is decremented by one when data is pushed onto the Stack with the PUSH instruction, and it is decremented by two when the return address is pushed onto the Stack with subroutine call or interrupt. The Stack Pointer is incremented by one when data is popped from the Stack with the POP instruction, and it is incremented by two when data is popped from the Stack with return from subroutine RET or return from interrupt RETI. The AVR Stack Pointer is implemented as two 8-bit registers in the I/O space. The number of bits actually used is implementation dependent. Note that the data space in some implementations of the AVR architecture is so small that only SPL is needed. In this case, the SPH Register will not be present.
7.5.1
SPH and SPL - Stack Pointer High and Stack Pointer Low
Bit 0x3E (0x5E) 0x3D (0x5D)
15 SP15 SP7 7
14 SP14 SP6 6 R/W R/W 0 0
13 SP13 SP5 5 R/W R/W 0 0
12 SP12 SP4 4 R/W R/W 0 0
11 SP11 SP3 3 R/W R/W 0 0
10 SP10 SP2 2 R/W R/W 0 0
9 SP9 SP1 1 R/W R/W 0 0
8 SP8 SP0 0 R/W R/W 0 0 SPH SPL
Read/Write
R/W R/W
Initial Value
0 0
13
8042A-AVR-07/09
ATmega16HVB/32HVB
7.6 Instruction Execution Timing
This section describes the general access timing concepts for instruction execution. The AVR CPU is driven by the CPU clock clkCPU, directly generated from the selected clock source for the chip. No internal clock division is used. Figure 7-4 shows the parallel instruction fetches and instruction executions enabled by the Harvard architecture and the fast-access Register File concept. This is the basic pipelining concept to obtain up to 1 MIPS per MHz with the corresponding unique results for functions per cost, functions per clocks, and functions per power-unit. Figure 7-4. The Parallel Instruction Fetches and Instruction Executions
T1 T2 T3 T4
clkCPU 1st Instruction Fetch 1st Instruction Execute 2nd Instruction Fetch 2nd Instruction Execute 3rd Instruction Fetch 3rd Instruction Execute 4th Instruction Fetch
Figure 7-5 shows the internal timing concept for the Register File. In a single clock cycle an ALU operation using two register operands is executed, and the result is stored back to the destination register. Figure 7-5. Single Cycle ALU Operation
T1 T2 T3 T4
clkCPU Total Execution Time Register Operands Fetch ALU Operation Execute Result Write Back
7.7
Reset and Interrupt Handling
The AVR provides several different interrupt sources. These interrupts and the separate Reset Vector each have a separate program vector in the program memory space. All interrupts are assigned individual enable bits which must be written logic one together with the Global Interrupt Enable bit in the Status Register in order to enable the interrupt. The lowest addresses in the program memory space are by default defined as the Reset and Interrupt Vectors. The complete list of vectors is shown in "Interrupts" on page 52. The list also determines the priority levels of the different interrupts. The lower the address the higher is the priority level. RESET has the highest priority.
14
8042A-AVR-07/09
ATmega16HVB/32HVB
When an interrupt occurs, the Global Interrupt Enable I-bit is cleared and all interrupts are disabled. The user software can write logic one to the I-bit to enable nested interrupts. All enabled interrupts can then interrupt the current interrupt routine. The I-bit is automatically set when a Return from Interrupt instruction - RETI - is executed. There are basically two types of interrupts. The first type is triggered by an event that sets the interrupt flag. For these interrupts, the Program Counter is vectored to the actual Interrupt Vector in order to execute the interrupt handling routine, and hardware clears the corresponding interrupt flag. Interrupt flags can also be cleared by writing a logic one to the flag bit position(s) to be cleared. If an interrupt condition occurs while the corresponding interrupt enable bit is cleared, the interrupt flag will be set and remembered until the interrupt is enabled, or the flag is cleared by software. Similarly, if one or more interrupt conditions occur while the Global Interrupt Enable bit is cleared, the corresponding interrupt flag(s) will be set and remembered until the Global Interrupt Enable bit is set, and will then be executed by order of priority. The second type of interrupts will trigger as long as the interrupt condition is present. These interrupts do not necessarily have interrupt flags. If the interrupt condition disappears before the interrupt is enabled, the interrupt will not be triggered. When the AVR exits from an interrupt, it will always return to the main program and execute one more instruction before any pending interrupt is served. Note that the Status Register is not automatically stored when entering an interrupt routine, nor restored when returning from an interrupt routine. This must be handled by software. When using the CLI instruction to disable interrupts, the interrupts will be immediately disabled. No interrupt will be executed after the CLI instruction, even if it occurs simultaneously with the CLI instruction. The following example shows how this can be used to avoid interrupts during the timed EEPROM write sequence. Assembly Code Example
in r16, SREG cli sbi EECR, EEMPE sbi EECR, EEPE out SREG, r16 ; restore SREG value (I-bit) ; store SREG value ; start EEPROM write ; disable interrupts during timed sequence
C Code Example
char cSREG; cSREG = SREG; /* store SREG value */ /* disable interrupts during timed sequence */ _CLI(); EECR |= (1<15
8042A-AVR-07/09
ATmega16HVB/32HVB
When using the SEI instruction to enable interrupts, the instruction following SEI will be executed before any pending interrupts, as shown in this example. Assembly Code Example
sei ; set Global Interrupt Enable sleep; enter sleep, waiting for interrupt ; note: will enter sleep before any pending ; interrupt(s)
C Code Example
_SEI(); /* set Global Interrupt Enable */ _SLEEP(); /* enter sleep, waiting for interrupt */ /* note: will enter sleep before any pending interrupt(s) */
7.7.1
Interrupt Response Time The interrupt execution response for all the enabled AVR interrupts is four clock cycles minimum. After four clock cycles the program vector address for the actual interrupt handling routine is executed. During this four clock cycle period, the Program Counter is pushed onto the Stack. The vector is normally a jump to the interrupt routine, and this jump takes three clock cycles. If an interrupt occurs during execution of a multi-cycle instruction, this instruction is completed before the interrupt is served. If an interrupt occurs when the MCU is in sleep mode, the interrupt execution response time is increased by four clock cycles. This increase comes in addition to the start-up time from the selected sleep mode. A return from an interrupt handling routine takes four clock cycles. During these four clock cycles, the Program Counter (two bytes) is popped back from the Stack, the Stack Pointer is incremented by two, and the I-bit in SREG is set.
16
8042A-AVR-07/09
ATmega16HVB/32HVB
8. AVR Memories
8.1 Overview
This section describes the different memories in the ATmega16HVB/32HVB. The AVR architecture has two main memory spaces, the Data Memory and the Program Memory space. In addition, the ATmega16HVB/32HVB features an EEPROM Memory for data storage. All three memory spaces are linear and regular.
8.2
In-System Reprogrammable Flash Program Memory
The ATmega16HVB/32HVB contains 16K/32K bytes On-chip In-System Reprogrammable Flash memory for program storage. Since all AVR instructions are 16 or 32 bits wide, the Flash is organized as 8K/16K x 16. The Flash memory has an endurance of at least 10,000 write/erase cycles. The ATmega16HVB/32HVB Program Counter (PC) is 13/14 bits wide, thus addressing the 8K/16K program memory locations. The operation of Boot Program section and associated Boot Lock bits for software protection are described in detail in "Boot Loader Support - Read-While-Write Self-Programming" on page 191. "Memory Programming" on page 208 contains a detailed description on Flash programming. Constant tables can be allocated within the entire program memory address space (see the LPM - Load Program Memory instruction description). Timing diagrams for instruction fetch and execution are presented in "Instruction Execution Timing" on page 14. Figure 8-1. Program Memory Map
Program Memory 0x0000
Application Flash Section
Boot Flash Section 0x1FFF/0x3FFF
8.3
SRAM Data Memory
Figure 8-2 on page 18 shows how the ATmega16HVB/32HVB SRAM Memory is organized.
17
8042A-AVR-07/09
ATmega16HVB/32HVB
The ATmega16HVB/32HVB is a complex microcontroller with more peripheral units than can be supported within the 64 locations reserved in the Opcode for the IN and OUT instructions. For the Extended I/O space from 0x60 - 0xFF in SRAM, only the ST/STS/STD and LD/LDS/LDD instructions can be used. The lower 1280/2304 data memory locations address both the Register File, the I/O memory, Extended I/O memory, and the internal data SRAM. The first 32 locations address the Register File, the next 64 location the standard I/O memory, then 160 locations of Extended I/O memory, and the next 1K/2K locations address the internal data SRAM. The five different addressing modes for the data memory cover: Direct, Indirect with Displacement, Indirect, Indirect with Pre-decrement, and Indirect with Post-increment. In the Register File, registers R26 to R31 feature the indirect addressing pointer registers. The direct addressing reaches the entire data space. The Indirect with Displacement mode reaches 63 address locations from the base address given by the Y- or Z-register. When using register indirect addressing modes with automatic pre-decrement and post-increment, the address registers X, Y, and Z are decremented or incremented. The 32 general purpose working registers, 64 I/O Registers, 160 Extended I/O Registers, and the 1K/2K bytes of internal data SRAM in the ATmega16HVB/32HVB are all accessible through all these addressing modes. The Register File is described in "General Purpose Register File" on page 12. Figure 8-2. Data Memory Map
Data Memory
32 Registers 64 I/O Registers 160 Ext I/O Reg. Internal SRAM (1K/2K x 8) 0x04FF/0x08FF
8.3.1 Data Memory Access Times This section describes the general access timing concepts for internal memory access. The internal data SRAM access is performed in two clkCPU cycles as described in Figure 8-3.
0x0000 - 0x001F 0x0020 - 0x005F 0x0060 - 0x00FF 0x0100
18
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 8-3. On-chip Data SRAM Access Cycles
T1 T2 T3
clkCPU Address Data WR Data RD
Compute Address Address valid
Memory Access Instruction
Next Instruction
8.4
EEPROM Data Memory
The ATmega16HVB/32HVB contains 512/1K bytes of data EEPROM memory. It is organized as a separate data space, in which single bytes can be read and written. The EEPROM has an endurance of at least 100,000 write/erase cycles. The access between the EEPROM and the CPU is described in the following, specifying the EEPROM Address Registers, the EEPROM Data Register, and the EEPROM Control Register. For a detailed description of EEPROM programming, see page 211 and page 216 respectively.
8.4.1
EEPROM Read/Write Access The EEPROM Access Registers are accessible in the I/O space. The write access time for the EEPROM is given in Table 8-1 on page 21. A self-timing function, however, lets the user software detect when the next byte can be written. If the user code contains instructions that write the EEPROM, some precautions must be taken. In order to prevent unintentional EEPROM writes, a specific write procedure must be followed. Refer to the description of the EEPROM Control Register for details on this. When the EEPROM is read, the CPU is halted for four clock cycles before the next instruction is executed. When the EEPROM is written, the CPU is halted for two clock cycles before the next instruction is executed.
8.5
I/O Memory
The I/O space definition of the ATmega16HVB/32HVB is shown in "Register Summary" on page 254. All ATmega16HVB/32HVB I/Os and peripherals are placed in the I/O space. All I/O locations may be accessed by the LD/LDS/LDD and ST/STS/STD instructions, transferring data between the 32 general purpose working registers and the I/O space. I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI and CBI instructions. In these registers, the value of single bits can be checked by using the SBIS and SBIC instructions. Refer to the instruction set section for more details. When using the I/O specific commands IN and OUT, 19
8042A-AVR-07/09
Read
Write
ATmega16HVB/32HVB
the I/O addresses 0x00 - 0x3F must be used. When addressing I/O Registers as data space using LD and ST instructions, 0x20 must be added to these addresses. The ATmega16HVB/32HVB is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in Opcode for the IN and OUT instructions. For the Extended I/O space from 0x60 - 0xFF in SRAM, only the ST/STS/STD and LD/LDS/LDD instructions can be used. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses should never be written. Some of the status flags are cleared by writing a logical one to them. Note that the CBI and SBI instructions will only operate on the specified bit, and can therefore be used on registers containing such status flags. The CBI and SBI instructions work with registers 0x00 to 0x1F only. The I/O and peripherals control registers are explained in later sections. 8.5.1 General Purpose I/O Registers The ATmega16HVB/32HVB contains three General Purpose I/O Registers. These registers can be used for storing any information, and they are particularly useful for storing global variables and Status Flags. General Purpose I/O Registers within the address range 0x00 - 0x1F are directly bit-accessible using the SBI, CBI, SBIS, and SBIC instructions.
8.6
8.6.1
Register Description
EEARH and EEARL- The EEPROM Address Register High and Low
Bit 0x22 (0x42) 0x21 (0x41) Bit Read/Write EEAR7 7 R R/W Initial Value 0 X EEAR6 6 R R/W 0 X EEAR5 5 R R/W 0 X EEAR4 4 R R/W 0 X EEAR3 3 R R/W 0 X EEAR2 2 R R/W 0 X 15 14 13 12 11 10 9 EEAR9 EEAR1 1 R/W R/W X X 8 EEAR8 EEAR0 0 R/W R/W X X EEARH EEARL
* Bits 15:10 - Res: Reserved Bits These bits are reserved bits in the ATmega16HVB/32HVB and will always read as zero. * Bits 9:0 - EEAR9:0: EEPROM Address The EEPROM Address Registers - EEAR specify the EEPROM address in the 512/1K bytes EEPROM space. The EEPROM data bytes are addressed linearly between 0 and 511/1023. The initial value of EEAR is undefined. A proper value must be written before the EEPROM may be accessed. 8.6.2 EEDR - The EEPROM Data Register
Bit 0x20 (0x40) Read/Write Initial Value 7 MSB R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 6 5 4 3 2 1 0 LSB R/W 0 EEDR
20
8042A-AVR-07/09
ATmega16HVB/32HVB
* Bits 7:0 - EEDR7:0: EEPROM Data For the EEPROM write operation, the EEDR Register contains the data to be written to the EEPROM in the address given by the EEAR Register. For the EEPROM read operation, the EEDR contains the data read out from the EEPROM at the address given by EEAR. 8.6.3 EECR - The EEPROM Control Register
Bit 0x1F (0x3F) Read/Write Initial Value 7 - R 0 6 - R 0 5 EEPM1 R/W X 4 EEPM0 R/W X 3 EERIE R/W 0 2 EEMPE R/W 0 1 EEPE R/W X 0 EERE R/W 0 EECR
* Bits 7:6 - Res: Reserved Bits These bits are reserved bits in the ATmega16HVB/32HVB and will always read as zero. * Bits 5, 4 - EEPM1 and EEPM0: EEPROM Programming Mode Bits The EEPROM Programming mode bit setting defines which programming action that will be triggered when writing EEPE. It is possible to program data in one atomic operation (erase the old value and program the new value) or to split the Erase and Write operations in two different operations. The Programming times for the different modes are shown in Table 8-1. While EEPE is set, any write to EEPMn will be ignored. During reset, the EEPMn bits will be reset to 0b00 unless the EEPROM is busy programming. Table 8-1.
EEPM1 0 0 1 1 Note:
EEPROM Mode Bits
EEPM0 0 1 0 1 Typ. Programming Time(1) 3.4 ms 1.8 ms 1.8 ms - Operation Erase and Write in one operation (Atomic Operation) Erase Only Write Only Reserved for future use
1. Actual timing depends on frequency of the Calibrated Fast RC Oscillator.
* Bit 3 - EERIE: EEPROM Ready Interrupt Enable Writing EERIE to one enables the EEPROM Ready Interrupt if the I bit in SREG is set. Writing EERIE to zero disables the interrupt. The EEPROM Ready interrupt generates a constant interrupt when EEPE is cleared. * Bit 2 - EEMPE: EEPROM Master Write Enable The EEMPE bit determines whether setting EEPE to one causes the EEPROM to be written. When EEMPE is set, setting EEPE within four clock cycles will write data to the EEPROM at the selected address If EEMPE is zero, setting EEPE will have no effect. When EEMPE has been written to one by software, hardware clears the bit to zero after four clock cycles. See the description of the EEPE bit for an EEPROM write procedure. * Bit 1 - EEPE: EEPROM Write Enable The EEPROM Write Enable Signal EEPE is the write strobe to the EEPROM. When address and data are correctly set up, the EEPE bit must be written to one to write the value into the
21
8042A-AVR-07/09
ATmega16HVB/32HVB
EEPROM. The EEMPE bit must be written to one before a logical one is written to EEPE, otherwise no EEPROM write takes place. The following procedure should be followed when writing the EEPROM (the order of steps 2 and 3 is not essential): 1. Wait until EEPE becomes zero. 2. Write new EEPROM address to EEAR (optional). 3. Write new EEPROM data to EEDR (optional). 4. Write a logical one to the EEMPE bit while writing a zero to EEPE in EECR. 5. Within four clock cycles after setting EEMPE, write a logical one to EEPE. Caution: An interrupt between step 4 and step 5 will make the write cycle fail, since the EEPROM Master Write Enable will time-out. If an interrupt routine accessing the EEPROM is interrupting another EEPROM access, the EEAR or EEDR Register will be modified, causing the interrupted EEPROM access to fail. It is recommended to have the Global Interrupt Flag cleared during all the steps to avoid these problems. When the write access time has elapsed, the EEPE bit is cleared by hardware. The user software can poll this bit and wait for a zero before writing the next byte. When EEPE has been set, the CPU is halted for two cycles before the next instruction is executed. Caution: A BOD reset during EEPROM write will invalidate the result of the ongoing operation. * Bit 0 - EERE: EEPROM Read Enable The EEPROM Read Enable Signal EERE is the read strobe to the EEPROM. When the correct address is set up in the EEAR Register, the EERE bit must be written to a logic one to trigger the EEPROM read. The EEPROM read access takes one instruction, and the requested data is available immediately. When the EEPROM is read, the CPU is halted for four cycles before the next instruction is executed. The user should poll the EEPE bit before starting the read operation. If a write operation is in progress, it is neither possible to read the EEPROM, nor to change the EEAR Register. The calibrated Oscillator is used to time the EEPROM accesses and the programming time will therefore depend on the calibrated oscillator frequency. Table 8-2 lists the typical programming time for EEPROM access from the CPU. Table 8-2.
Symbol EEPROM write (from CPU)
EEPROM Programming Time
Number of Calibrated RC Oscillator Cycles 27200 Typ Programming Time, fOSC = 8 MHz 3.4 ms
The following code examples show one assembly and one C function for writing to the EEPROM. The examples assume that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts will occur during execution of these functions. The examples also assume that no Flash Boot Loader is present in the software. If such code is present, the EEPROM write function must also wait for any ongoing SPM command to finish.
22
8042A-AVR-07/09
ATmega16HVB/32HVB
Assembly Code Example
EEPROM_write: ; Wait for completion of previous write sbic EECR,EEPE rjmp EEPROM_write ; Set up address (r18:r17) in address register out EEARH, r18 out EEARL, r17 ; Write data (r16) to data register out EEDR,r16 ; Write logical one to EEMPE sbi EECR,EEMPE ; Start eeprom write by setting EEPE sbi EECR,EEPE ret
C Code Example
void EEPROM_write(unsigned int uiAddress, unsigned char ucData) { /* Wait for completion of previous write */ while(EECR & (1<The next code examples show assembly and C functions for reading the EEPROM. The examples assume that interrupts are controlled so that no interrupts will occur during execution of these functions.
23
8042A-AVR-07/09
ATmega16HVB/32HVB
Assembly Code Example
EEPROM_read: ; Wait for completion of previous write sbic EECR,EEPE rjmp EEPROM_read ; Set up address (r18:r17) in address register out EEARH, r18 out EEARL, r17 ; Start eeprom read by writing EERE sbi EECR,EERE ; Read data from data register in ret r16,EEDR
C Code Example
unsigned char EEPROM_read(unsigned int uiAddress) { /* Wait for completion of previous write */ while(EECR & (1<8.6.4
GPIOR2 - General Purpose I/O Register 2
Bit 0x2B (0x4B) Read/Write Initial Value 7 MSB R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 6 5 4 3 2 1 0 LSB R/W 0 GPIOR2
8.6.5
GPIOR1 - General Purpose I/O Register 1
Bit 0x2A (0x4A) Read/Write Initial Value 7 MSB R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 6 5 4 3 2 1 0 LSB R/W 0 GPIOR1
8.6.6
GPIOR0 - General Purpose I/O Register 0
Bit 0x1E (0x3E) Read/Write Initial Value 7 MSB R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 R/W 0 6 5 4 3 2 1 0 LSB R/W 0 GPIOR0
24
8042A-AVR-07/09
ATmega16HVB/32HVB
9. System Clock and Clock Options
9.1 Clock Systems and their Distribution
Figure 9-1 presents the principal clock systems in the AVR and their distribution. All of the clocks need not be active at a given time. In order to reduce power consumption, the clocks to modules not being used can be halted by using different sleep modes, as described in "Power Management and Sleep Modes" on page 35. The clock systems are detailed below. Figure 9-1. Clock Distribution
Coulomb Counter ADC
CPU CORE
RAM
FLASH and EEPROM
Voltage ADC
Other I/O Modules
clkCCADC
clkFLASH
clkVADC VADC Prescaler
clkCPU
clkI/O
Oscillator Sampling Interface
1/4
Watchdog Timer
TWI Disconnect delay
AVR Clock Control
Battery Protection Reset Logic
System Clock Prescaler
Slow RC Oscillator
Ultra Low Power RC Oscillator
Fast RC Oscillator
9.1.1
CPU Clock - clkCPU The CPU clock is routed to parts of the system concerned with operation of the AVR core. Examples of such modules are the General Purpose Register File, the Status Register and the data memory holding the Stack Pointer. Halting the CPU clock inhibits the core from performing general operations and calculations.
9.1.2
I/O Clock - clkI/O The I/O clock is used by the majority of the I/O modules. The I/O clock is also used by the External Interrupt module, but note that some external interrupts are detected by asynchronous logic, allowing such interrupts to be detected even if the I/O clock is halted.
9.1.3
Flash Clock - clkFLASH The Flash clock controls operation of the Flash interface. The Flash clock is usually active simultaneously with the CPU clock.
25
8042A-AVR-07/09
ATmega16HVB/32HVB
9.1.4 Voltage ADC Clock - clkVADC The Voltage ADC is provided with a dedicated clock domain. The VADC clock is automatically prescaled relative to the System Clock Prescalers setting by the VADC Prescaler, giving a fixed VADC clock at 1 MHz. 9.1.5 Coulomb Counter ADC Clock - clkCCADC The Coulomb Counter ADC is provided with a dedicated clock domain. This allows operating the Coulomb Counter ADC in low power modes like Power-save for continuous current measurements. 9.1.6 Watchdog Timer and Battery Protection Clock The Watchdog Timer and Battery Protection are provided with a dedicated clock domain. This allows operation in all modes except Power-off. It also allows very low power operation by utilizing an Ultra Low Power RC Oscillator dedicated to this purpose.
9.2
Clock Sources
The following section describes the clock sources available in the device. The clocks are input to the AVR clock generator, and routed to the appropriate modules. The ATmega16HVB/32HVB has 3 on-board oscillator used to clock the internal logic. Table 9-1 shows the clock sources and their usage. Table 9-1. Available Clock Sources.
Clock Source Calibrated Fast RC Oscillator Ultra Low Power RC Oscillator Slow RC Oscillator Usage The clock source for the CPU, I/O, Flash, and Voltage ADC. The clock source for the Watchdog Timer, Battery Protection, Coulomb Counter ADC, Bandgap Buffer Short Circuit Detector, and SMBus Connect/Disconnect. Used by the Oscillator Sampling Interface (OSI).
9.2.1
Calibrated Fast RC Oscillator The calibrated Fast RC Oscillator by default provides a 8.0 MHz clock. The frequency is nominal value at 25C. This clock will operate with no external components. During reset, hardware loads the calibration byte into the FOSCCAL Register and thereby automatically calibrates the Fast RC Oscillator. At 25C, this calibration gives a frequency of 8 MHz 1%. The oscillator can be calibrated to any frequency in the range 7.3 - 8.1 MHz by changing the FOSCCAL register. For more information on the pre-programmed calibration value, see the section "Reading the Signature Row from Software" on page 199. Note that the frequency of the system clock is given by the "System Clock Prescaler" on page 28.
26
8042A-AVR-07/09
ATmega16HVB/32HVB
When this Oscillator is selected, start-up times are determined by the SUT Fuses as shown in Table 9-2 on page 27. Table 9-2.
SUT2:0 000 001 010 011 100 101 110 111 Notes:
(1)
Start-up times for the calibrated Fast RC Oscillator clock selection
Start-up Time from Power-save 6 CK 6 CK 6 CK 6 CK 6 CK 6 CK 6 CK 6 CK Additional Delay from Reset, Typical Values(2) 14 CK + 4 ms 14 CK + 8 ms 14 CK + 16 ms 14 CK + 32 ms 14 CK + 64 ms 14 CK + 128 ms 14 CK + 256 ms 14 CK + 512 ms
1. The device is shipped with this option selected. 2. The actual value of the added, selectable 4- 512 ms delay depends on the actual frequency of the "Ultra Low Power RC Oscillator" on page 27. See Table 9-3 on page 28 and "Electrical Characteristics" on page 228
9.2.2
Slow RC Oscillator The Slow RC Oscillator provides a 131 kHz clock (typical value, refer to section "Electrical Characteristics" on page 228). This clock can be used as a timing reference for run-time calibration of the Fast RC Oscillator and for accurately determining the actual ULP Oscillator frequency, refer to "OSI - Oscillator Sampling Interface" on page 29 for details. To provide good accuracy when used as a timing reference, the Slow RC Oscillator has calibration bytes stored in the signature address space, refer to section "Reading the Signature Row from Software" on page 199 for details. The actual clock period of the Slow RC Oscillator in s as a function of temperature is given by:
(T - T HOT ) Slow RC word - Slow RC temp prediction word -------------------------64 Slow RC period = ----------------------------------------------------------------------------------------------------------------------------------------------------------1024
where T is the die temperature in Kelvin and THOT is the calibration temperature stored in the signature row. The die temperature can be found using the Voltage ADC, refer to section "Voltage ADC - 7-channel General Purpose 12-bit Sigma-Delta ADC" on page 117 for details. 9.2.3 Ultra Low Power RC Oscillator The Ultra Low Power RC Oscillator (ULP Oscillator) provides a 128 kHz clock (typical value, refer to section "Electrical Characteristics" on page 228). This oscillator provides the clock for the Watchdog Timer and Battery Protection modules. The actual ULP Oscillator frequency depends on process variations and temperature, see "Electrical Characteristics" on page 228. The Oscillator is automatically enabled in all operational modes. It is also enabled during reset. There are two alternative methods for determining the actual clock period of the ULP Oscillator:
27
8042A-AVR-07/09
ATmega16HVB/32HVB
1. To determine the accurate clock period as a function of die temperature, if needed by the application, the Oscillator Sampling Interface should be used. Refer to section "OSI - Oscillator Sampling Interface" on page 29 for details. 2. To determine a fixed value for the actual clock period independent of the die temperature, for example to determine the best setting of the Battery Protection timing, use the calibration byte ULP_RC_FRQ stored in the signature address space, refer to section "Reading the Signature Row from Software" on page 199 for details.
9.3
Clock Startup Sequence
When the CPU wakes up from Power-save, the CPU clock source is used to time the start-up, ensuring a stable clock before instruction execution starts. When the CPU starts from reset, there is an additional delay allowing the voltage regulator to reach a stable level before commencing normal operation. The Ultra Low Power RC Oscillator is used for timing this real-time part of the start-up time. Start-up times are determined by the SUT Fuses as shown in Table 9-2 on page 27. The number of Ultra Low Power RC Oscillator cycles used for each time-out is shown in Table 9-3. Table 9-3. Number of Ultra Low Power RC Oscillator Cycles
Typ Time-out(1) 4 ms 8 ms 16 ms 32 ms 64 ms 128 ms 256 ms 512 ms Note: Number of Cycles 512 1K 2K 4K 8K 16K 32K 64K
1. The actual value depends on the actual clock period of the Ultra Low Power RC Oscillator, refer to "Ultra Low Power RC Oscillator" on page 27 for details.
9.4
Clock Output
The CPU clock divided by 2 can be output to the PB1 pin. The CPU can enable the clock output function by setting the CKOE bit in the MCU Control Register. The clock will not run in any sleep modes.
9.5
System Clock Prescaler
The ATmega16HVB/32HVB has a System Clock Prescaler, used to prescale the Calibrated Fast RC Oscillator. The system clock can be divided by setting the "CLKPR - Clock Prescale Register" on page 32, and this enables the user to decrease or increase the system clock frequency as the requirement for power consumption and processing power changes. This system clock will affect the clock frequency of the CPU and all synchronous peripherals. clkI/O, clkCPU and clkFLASH are divided by a factor as shown in Table 9-4 on page 33. When switching between prescaler settings, the System Clock Prescaler ensures that no glitches occurs in the clock system. It also ensures that no intermediate frequency is higher than
28
8042A-AVR-07/09
ATmega16HVB/32HVB
neither the clock frequency corresponding to the previous setting, nor the clock frequency corresponding to the new setting. The ripple counter that implements the prescaler runs at the frequency of the undivided clock, and may be faster than the CPU's clock frequency. It is not possible to determine the state of the prescaler, and the exact time it takes to switch from one clock division to the other cannot be exactly predicted. From the time the CLKPS values are written, it takes between T1 + T2 and T1 + 2*T2 before the new clock frequency is active. In this interval, two active clock edges are produced. Here, T1 is the previous clock period, and T2 is the period corresponding to the new prescaler setting. To avoid unintentional changes of clock frequency, a special write procedure must be followed to change the CLKPS bits: 1. Write the Clock Prescaler Change Enable (CLKPCE) bit to one and all other bits in CLKPR to zero. 2. Within four cycles, write the desired value to CLKPS while writing a zero to CLKPCE. Interrupts must be disabled when changing prescaler setting to make sure the write procedure is not interrupted.
9.6
VADC Clock Prescaler
The VADC clock will be automatically prescaled relative to the System Clock Prescaler settings, see "System Clock Prescaler" on page 28. Depending on the Clock Prescale Select bits, CLKPS1..0, the VADC clock, clkVADC, will be prescaled by 8, 4, 2 or 1 as shown in Table 9-5 on page 33.
9.7
9.7.1
OSI - Oscillator Sampling Interface
Features * * * *
Runtime selectable oscillator input (Slow RC or ULP RC Oscillator) 7 bit prescaling of the selected oscillator Software read access to the phase of the prescaled clock Input capture trigger source for Timer/Counter0
9.7.2
Overview The Oscillator Sampling Interface (OSI) enables sampling of the Slow RC and Ultra Low Power RC (ULP) oscillators in ATmega16HVB/32HVB. OSI can be used to calibrate the Fast RC Oscillator runtime with high accuracy. OSI can also provide an accurate reference for compensating the ULP Oscillator frequency drift. This is useful for modules with high-precision requirements, such as the Coulomb Counter. The prescaled oscillator phase can be continuously read by the CPU through the OSICSR register. In addition, the input capture function of Timer/Counter0 can be set up to trigger on the rising edge of the prescaled clock. This enables accurate measurements of the oscillator frequencies relative to the Fast RC Oscillator. A simplified block diagram of the Oscillator Sampling Interface is shown in Figure 9-2 on page 30.
29
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 9-2. Oscillator Sampling Interface Block Diagram
Databus
OSICSR
OSISEL0 Ultra Low Power RC Oscillator
OSCILLATOR SELECT
7 bit prescaler
Edge Detector
osi_posedge
Slow RC Oscillator
Fast RC Oscillator
The osi_posedge signal pulses on each rising edge of the prescaled clock. This signal is not directly accessible by the CPU, but can be used to trigger the input capture function of Timer/Counter0. Using OSI in combination with the input capture function of Timer/Counter0 facilitates accurate measurement of the oscillator frequencies with a minimum of CPU calculation. Refer to "Timer/Counter (T/C0,T/C1)" on page 82 for details on how to enable the Input Capture function.
30
8042A-AVR-07/09
ATmega16HVB/32HVB
9.7.3 Usage The Slow RC oscillator represents a highly predictable and accurate clock source over the entire temperature range and provides an excellent reference for calibrating the Fast RC oscillator runtime. Typically, runtime calibration is needed to provide an accurate Fast RC frequency for asynchronous serial communication in the complete temperature range. The Slow RC frequency at 85C and the Slow RC temperature coefficient are stored in the signature row. These characteristics can be used to calculate the actual Slow RC clock period at a given temperature with high precision. Refer to "Slow RC Oscillator" on page 27 for details. By measuring the number of CPU cycles of one or more prescaled Slow RC clock periods, the actual Fast RC oscillator clock period can be determined. The Fast RC clock period can then be adjusted by writing to the FOSCCAL register. The new Fast RC clock period after calibration should be verified by repeating the measurement and repeating the calibration if necessary. The Fast RC clock period as a function of the Slow RC clock period is given by:
128 n T FastRC = T SlowRC -----------------------------------------------------------------------------------------------------------------------------------------------number of CPU cycles in n prescaled Slow RC periods
where n is the number of prescaled Slow RC periods that is used in the measurement. Using more prescaled Slow RC periods decreases the measurement error, but increases the time consumed for calibration. Note that the Slow RC Oscillator needs very short time to stabilize after being enabled by the OSI module. Hence, the calibration algorithm may use the time between the first and second osi_posedge as time reference for calculations. Another usage of OSI is determining the ULP frequency accurately. The ULP frequency at 85C and the ULP temperature coefficient are stored in the signature row, allowing the ULP frequency to be calculated directly. However, the ULP frequency is less predictable over temperature than the Slow RC oscillator frequency, therefore a more accurate result can be obtained by calculating the ratio between the Slow RC and ULP oscillators. This is done by sampling both the ULP and Slow RC oscillators and comparing the results. When the ratio is known, the actual ULP frequency can be determined with high accuracy. The ULP RC clock period as a function of the Slow RC clock period is given by:
number of CPU cycles in n prescaled ULP RC periods T ULPRC = T SlowRC -----------------------------------------------------------------------------------------------------------------------------------------------number of CPU cycles in n prescaled Slow RC periods
where n is the number of prescaled ULP RC and Slow RC periods that is used in the measurement. Using more prescaled ULP RC and Slow RC periods decreases the measurement error, but increases the time consumed for calibration. Note that the FOSCCAL register must be kept at a constant value during this operation to ensure accurate results. These clock period calculations should be performed again when there is a significant change in die temperature since the previous calculation. The die temperature can be found using the Voltage ADC, refer to section "Voltage ADC - 7-channel General Purpose 12-bit Sigma-Delta ADC" on page 117 for details.
31
8042A-AVR-07/09
ATmega16HVB/32HVB
9.8
9.8.1
Register Description
FOSCCAL - Fast RC Oscillator Calibration Register
Bit (0x66) Read/Write Initial Value 7 FCAL7 R/W 6 FCAL6 R/W 5 FCAL5 R/W 4 FCAL4 R/W 3 FCAL3 R/W 2 FCAL2 R/W 1 FCAL1 R/W 0 FCAL0 R/W FOSCCAL
Device Specific Calibration Value
* Bits 7:0 - FCAL7:0: Fast RC Oscillator Calibration Value The Fast RC Oscillator Calibration Register is used to trim the Fast RC Oscillator to remove process variations from the oscillator frequency. The factory-calibrated value is automatically written to this register during chip reset, giving an oscillator frequency of approximately 8.0 MHz at 25C. The application software can write this register to change the oscillator frequency. The oscillator can be run-time calibrated to any frequency in the range 7.3 - 8.1 MHz. Calibration outside that range is not guaranteed. Note that this oscillator is used to time EEPROM and Flash write accesses, and these write times will be affected accordingly. If the EEPROM or Flash are written, do not calibrate to more than 8.1 MHz. Otherwise, the EEPROM or Flash write may fail. The FCAL[7:5] bits determine the range of operation for the oscillator. Setting these bits to 0b000 gives the lowest frequency range, setting this bit to 0b111 gives the highest frequency range. The frequency ranges are overlapping. A setting of for instance FOSCCAL = 0x1F gives a higher frequency than FOSCCAL = 0x20. The FCAL[4:0] bits are used to tune the frequency within the selected range. A setting of 0x00 gives the lowest frequency in that range, and a setting of 0x1F gives the highest frequency in the range. Incrementing FCAL[4:0] by 1 will give a frequency increment of less than 1% in the frequency range 7.3 - 8.1 MHz. With an accurate time reference, an oscillator accuracy of 0.5% can be achieved after calibration. The frequency will drift with temperature, so run-time calibration will be required to maintain the accuracy. Refer to "OSI - Oscillator Sampling Interface" on page 29 for details. 9.8.2 MCUCR - MCU Control Register
Bit 0x35 (0x55) Read/Write Initial Value 7 -- R 0 6 - R 0 5 CKOE R/W 0 4 PUD R/W 0 3 - R 0 2 - R 0 1 IVSEL R/W 0 0 IVCE R/W 0 MCUCR
* Bit 5 - CKOE: Clock Output When this bit is written to one, the CPU clock divided by 2 is output on the PB1 pin. 9.8.3 CLKPR - Clock Prescale Register
Bit (0x61) Read/Write Initial Value
7 CLKPCE R/W 0
6 - R 0
5 - R 0
4 - R 0
3 - R 0
2 - R 0
1 CLKPS1 R/W 1
0 CLKPS0 R/W 1 CLKPR
32
8042A-AVR-07/09
ATmega16HVB/32HVB
* Bit 7 - CLKPCE: Clock Prescaler Change Enable The CLKPCE bit must be written to logic one to enable change of the CLKPS bits. The CLKPCE bit is only updated when the other bits in CLKPR are simultaneously written to zero. CLKPCE is cleared by hardware four cycles after it is written or when CLKPS bits are written. Rewriting the CLKPCE bit within this time-out period does neither extend the time-out period, or clear the CLKPCE bit. * Bit 1:0 - CLKPS1:0: Clock Prescaler Select Bit 1..0 These bits define the division factor between the selected clock source and the internal system clock. These bits can be written run-time to vary the clock frequency to suit the application requirements. As the divider divides the master clock input to the MCU, the speed of all synchronous peripherals is reduced when a division factor is used. The division factors are given in Table 9-4 on page 33. Note that writing to the System Clock Prescaler Select bits will abort any ongoing VADC conversion. Table 9-4. System Clock Prescaler Select
CLKPS1 0 0 1 1 CLKPS0 0 1 0 1 Clock Division Factor 1 2 4 8
Table 9-5.
VADC Clock Prescaling(1)
CLKPS1 0 0 1 1 CLKPS0 0 1 0 1 VADC Division Factor 8 4 2 1
Note:
1. When changing Prescaler value, the VADC Prescaler will automatically change frequency of the VADC clock and abort any ongoing conversion.
9.8.4
OSICSR - Oscillator Sampling Interface Control and Status Register
Bit 0x17 (0x37) Read/Write Initial Value
7 - R 0
6 - R 0
5 - R 0
4 OSISEL0 R/W 0
3 - R 0
2 - R 0
1 OSIST R 0
0 OSIEN R/W 0 OSICSR
* Bits 7:5,3:2 - RES: Reserved bits These bits are reserved bits in the ATmega16HVB/32HVB and will always read as zero.
33
8042A-AVR-07/09
ATmega16HVB/32HVB
* Bit 4 - OSISEL0: Oscillator Sampling Interface Select 0 Table 9-6. OSISEL Bit Description
OSISEL0 0 1 Oscillator source ULP Oscillator Slow RC Oscillator
* Bit 1 - OSIST: Oscillator Sampling Interface Status This bit continuously displays the phase of the prescaled clock. This bit can be polled by the CPU to determine the rising and falling edges of the prescaled clock. * Bit 0 - OSIEN: Oscillator Sampling Interface Enable Setting this bit enables the Oscillator Sampling Interface. When this bit is cleared, the Oscillator Sampling Interface is disabled.
Notes: 1. The prescaler is reset each time the OSICSR register is written, and hence each time a new oscillator source is selected. 2. Enabling the OSI module and selecting Slow RC Oscillator as input source is the only way to enable the Slow RC Oscillator. The Slow RC Oscillator will not run in any other modes.
34
8042A-AVR-07/09
ATmega16HVB/32HVB
10. Power Management and Sleep Modes
Sleep modes enable the application to shut down unused modules in the MCU, thereby saving power. The AVR provides various sleep modes allowing the user to tailor the power consumption to the application's requirements.
10.1
Sleep Modes
Figure 9-1 on page 25 presents the different clock systems in the ATmega16HVB/32HVB, and their distribution. The figure is helpful in selecting an appropriate sleep mode. The different sleep modes and their wake up sources is summarized in Table 10-1, and Figure 10-1 on page 36 shows a sleep mode state diagram.
Table 10-1.
Wake-up Sources for Sleep Modes
Wake-up sources
SMBus Address match and Bus Connect/Disconnect
X X X
Mode Idle ADC Noise Reduction Power-save Power-off Notes:
X X X
X X X
X X X
X X X
X X X
X X
X X X
X X
X
X X X X
X X
1. Discharge FET must be switched off for Charge Detect to be active. 2. When waking from Power-off the Charger Detect will generate a Power-on Reset (POR). From other sleep modes a charger detect interrupt will wake-up chip.
To enter any of the sleep modes, the SE bit in SMCR, see "SMCR - Sleep Mode Control Register" on page 39, must be written to logic one and a SLEEP instruction must be executed. The SM2..0 bits in the SMCR Register select which sleep mode will be activated by the SLEEP instruction. See Table 10-3 on page 40 for a summary. If an enabled interrupt occurs while the MCU is in a sleep mode, the MCU wakes up. The MCU is then halted for four cycles in addition to the start-up time, executes the interrupt routine, and resumes execution from the instruction following SLEEP. The contents of the register file and SRAM are unaltered when the device wakes up from any sleep mode except Power-off. If a reset occurs during sleep mode, the MCU wakes up and executes from the Reset Vector.
8042A-AVR-07/09
Voltage Regulator warning
Bandgap Buffer Short Circuit Detection
SPM/EEPROM Ready
External Interrupts
Charger Detect(1)(2)
Battery Protection Interrupts
Wake-up on Regular Current
Other I/O
CC-ADC
V-ADC
WDT
35
ATmega16HVB/32HVB
Figure 10-1. Sleep Mode State Diagram
Reset From all States Except Power-on Reset
RESET
Reset Time-out
Active
Sleep Interrupt Sleep Interrupt Sleep
Interrupt
ADC NRM
Idle
Sleep or Black-out Detection Black-out Detection
Power-save
Black-out Detection
Black-out Detection
Power-off
Charger Connected
. Table 10-2. Active modules in different Sleep Modes
Mode Module RCOSC_FAST RCOSC_ULP RCOSC_SLOW OSI CPU Flash 8-bit Timer/16-bit Timer TWI/SMBus SPI V-ADC CC-ADC Active X X X(1) X X X X X X X X X X X X X X X X X(2) X(2) Idle X X X(1) X ADC Noise Reduction X X Power-save X X Power-off
36
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 10-2. Active modules in different Sleep Modes (Continued)
Mode Module External Interrupts Battery Protection Watchdog Timer Voltage Regulator Bandgap Reference FET Driver CHARGER_DETECT Notes: 1. 2. 3. 4.
(3)
Active X X X X X X X
Idle X X X X X X X
ADC Noise Reduction X X X X X X X
Power-save X X X X(4) X X X
Power-off
X
Runs only when OSI is enabled and RCOSC_SLOW is selected as source for OSI. Address Match and Bus Connect/Disconnect Wake-up only Discharge FET must be switched off for Charger Detect to be enabled. VREGMON interrupt (Regulator Operation Condition Warning) not available.
10.2
Idle Mode
When the SM2..0 bits are written to 000, the SLEEP instruction makes the MCU enter Idle mode, stopping the CPU but allowing all peripheral functions to continue operating. This sleep mode basically halts clkCPU and clk FLASH , while allowing the other clocks to run. Idle mode enables the MCU to wake up from external triggered interrupts as well as internal ones like the Timer Overflow interrupt.
10.3
ADC Noise Reduction
When the SM2:0 bits are written to 001, the SLEEP instruction makes the MCU enter ADC Noise Reduction mode, stopping the CPU but allowing the Voltage ADC (V-ADC), Voltage Regulator Monitor (VREGMON), Watchdog Timer (WDT), Coulomb Counter (CC), Current Battery Protection (CBP), and the Ultra Low Power RC Oscillator (RCOSC_ULP) to continue operating. This sleep mode basically halts clkI/O, clkCPU, and clkFLASH, while allowing the other clocks to run. This improves the noise environment for the Voltage ADC, enabling higher accuracy on measurements.
10.4
Power-save Mode
When the SM2..0 bits are written to 011, the SLEEP instruction makes the MCU enter Powersave mode. In this mode, the internal Fast RC Oscillator (RCOSC_FAST) is stopped, while Watchdog Timer (WDT), Coulomb Counter (CC), Current Battery Protection (CBP) and the Ultra Low Power RC Oscillator (RCOSC_ULP) continue operating. This mode will be the default mode when application software does not require operation of CPU, Flash or any of the peripheral units running at the Fast internal Oscillator (RCOSC_FAST). If the current through the sense resistor is so small that the Coulomb Counter cannot measure it accurately, Regular Current detection should be enabled to reduce power consumption. The WDT keeps accurately track of the time so that battery self discharge can be calculated.
37
8042A-AVR-07/09
ATmega16HVB/32HVB
Note that if a level triggered interrupt is used for wake-up from Power-save mode, the changed level must be held for some time to wake up the MCU. Refer to "External Interrupts" on page 58 for details. When waking up from Power-save mode, there is a delay from the wake-up condition occurs until the wake-up becomes effective. This allows the clock to restart and become stable after having been stopped. The wake-up period is defined in "Clock Sources" on page 26.
10.5
Power-off Mode
When the SM2..0 bits are written to 100 and the SE bit is set, the SLEEP instruction makes the CPU shut down the Voltage Regulator, leaving only the Charger Detect Circuitry operational. To ensure that the MCU enters Power-off mode only when intended, the SLEEP instruction must be executed within 4 clock cycles after the SM2..0 bits are written. The MCU will reset when returning from Power-off mode.
Note: Before entering Power-off sleep mode, interrupts should be disabled by software. Otherwise interrupts may prevent the SLEEP instruction from being executed within the time limit.
10.6
Power Reduction Register
The Power Reduction Register (PRR), see "PRR0 - Power Reduction Register 0" on page 40, provides a method to stop the clock to individual peripherals to reduce power consumption. The current state of the peripheral is frozen and the I/O registers can not be read or written. Resources used by the peripheral when stopping the clock will remain occupied, hence the peripheral should in most cases be disabled before stopping the clock. Waking up a module, which is done by clearing the bit in PRR, puts the module in the same state as before shutdown. Module shutdown can be used in Idle mode and Active mode to significantly reduce the overall power consumption. In all other sleep modes, the clock is already stopped.
10.7
Minimizing Power Consumption
There are several issues to consider when trying to minimize the power consumption in an AVR controlled system. In general, sleep modes should be used as much as possible, and the sleep mode should be selected so that as few as possible of the device's functions are operating. All functions not needed should be disabled. In particular, the following modules may need special consideration when trying to achieve the lowest possible power consumption.
10.7.1
Watchdog Timer If the Watchdog Timer is not needed in the application, the module should be turned off. If the Watchdog Timer is enabled, it will be enabled in all sleep modes except Power-off. The Watchdog Timer current consumption is significant only in Power-save mode. Refer to "Watchdog Timer" on page 46 for details on how to configure the Watchdog Timer.
10.7.2
Port Pins When entering a sleep mode, all port pins should be configured to use minimum power. The most important is then to ensure that no pins drive resistive loads. In sleep modes where both the I/O clock (clkI/O) and the ADC clock (clkADC) are stopped, the input buffers of the device will be disabled. This ensures that no power is consumed by the input logic when not needed. In some cases, the input logic is needed for detecting wake-up conditions, and it will then be enabled. Refer to the section "Digital Input Enable and Sleep Modes" on page 71 for details on which pins are enabled. If the input buffer is enabled and the input signal is left floating or have an analog signal level close to VREG/2, the input buffer will use excessive power. 38
8042A-AVR-07/09
ATmega16HVB/32HVB
For analog input pins, the digital input buffer should be disabled at all times. An analog signal level close to VREG/2 on an input pin can cause significant current even in active mode. Digital input buffers can be disabled by writing to the Digital Input Disable Register. Refer to "DIDR0 - Digital Input Disable Register 0" on page 122 for details. 10.7.3 On-chip Debug System A programmed DWEN Fuse enables some parts of the clock system to be running in all sleep modes. This will increase the power consumption while in sleep. Thus, the DWEN Fuse should be disabled when debugWire is not used. 10.7.4 Battery Protection If one of the Battery Protection features is not needed by the application, this feature should be disabled, see "BPCR - Battery Protection Control Register" on page 141. The current consumption in the Battery Protection circuitry is only significant in Power-save mode. Disabling both FETs will automatically disable the Battery Protection module in order to save power. The bandgap reference should always be enabled whenever Battery Protection is enabled. 10.7.5 Voltage ADC If enabled, the V-ADC will consume power independent of sleep mode. To save power, the VADC should be disabled when not used, and before entering Power-save sleep mode. See "Voltage ADC - 7-channel General Purpose 12-bit Sigma-Delta ADC" on page 117 for details on V-ADC operation. 10.7.6 Coulomb Counter If enabled, the CC-ADC will consume power independent of sleep mode. To save power, the CC-ADC should be disabled when not used, or set in Regular Current detection mode. See "Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC" on page 108 for details on CCADC operation. 10.7.7 Bandgap Voltage Reference If enabled, the Bandgap reference will consume power independent of sleep mode. To save power, the Bandgap reference should be disabled when not used as reference for the Voltage ADC, the Coloumb Counter or Battery Protection. See "Voltage Reference and Temperature Sensor" on page 123 for details.
10.8
10.8.1
Register Description
SMCR - Sleep Mode Control Register The Sleep Mode Control Register contains control bits for power management.
Bit 0x33 (0x53) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 SM2 R/W 0 2 SM1 R/W 0 1 SM0 R/W 0 0 SE R/W 0 SMCR
* Bits 7:4 - Res: Reserved Bits These bits are reserved bits in the ATmega16HVB/32HVB, and will always read as zero. * Bits 3:1 - SM2:0: Sleep Mode Select Bits 2, 1 and 0
39
8042A-AVR-07/09
ATmega16HVB/32HVB
These bits select between the four available sleep modes as shown in Table 10-3. Table 10-3.
SM2 0 0 0 0 1 1 1 1
Sleep Mode Select
SM1 0 0 1 1 0 0 1 1 SM0 0 1 0 1 0 1 0 1 Sleep Mode Idle ADC Noise Reduction Reserved Power-save Power-off Reserved Reserved Reserved
* Bit 0 - SE: Sleep Enable The SE bit must be written to logic one to make the MCU enter the sleep mode when the SLEEP instruction is executed. To avoid the MCU entering the sleep mode unless it is the programmer's purpose, it is recommended to write the Sleep Enable (SE) bit to one just before the execution of the SLEEP instruction and to clear it immediately after waking up. 10.8.2 PRR0 - Power Reduction Register 0
Bit (0x64) Read/Write Initial Value 7 - R 0 6 PRTWI R/W 0 5 PRVRM R/W 0 4 - R 0 3 PRSPI R/W 0 2 PRTIM1 R/W 0 1 PRTIM0 R/W 0 0 PRVADC R/W 0 PRR0
* Bit 7, 4 - Res: Reserved bits These bits are reserved for future use. For compatibility with future devices, these bits must be written to zero when PRR0 is written. * Bit 6 - PRTWI: Power Reduction TWI Writing a logic one to this bit shuts down the TWI by stopping the clock to the module. When waking up the TWI again, the TWI should be re initialized to ensure proper operation. * Bit 5 - PRVRM: Power Reduction Voltage Regulator Monitor Writing a logic one to this bit shuts down the Voltage Regulator Monitor interface by stopping the clock of the module. * Bit 3 - PRSPI: Power Reduction Serial Peripheral Interface Writing logic one to this bit shuts down the Serial Peripheral Interface by stopping the clock to the module. When waking up the SPI again, the SPI should be reinitialized to ensure proper operation. * Bit 2 - PRTIM1: Power Reduction Timer/Counter1 Writing a logic one to this bit shuts down the Timer/Counter1 module. When the Timer/Counter1 is enabled, operation will continue like before the shutdown.
40
8042A-AVR-07/09
ATmega16HVB/32HVB
* Bit 1 - PRTIM0: Power Reduction Timer/Counter0 Writing a logic one to this bit shuts down the Timer/Counter0 module. When the Timer/Counter0 is enabled, operation will continue like before the shutdown. * Bit 0 - PRVADC: Power Reduction V-ADC Writing a logic one to this bit shuts down the V-ADC. Before writing the PRVADC bit, make sure that the VADEN bit is cleared to minimize the power consumption.
Note: V-ADC control registers can be updated even if the PRVADC bit is set.
41
8042A-AVR-07/09
ATmega16HVB/32HVB
11. System Control and Reset
11.1 Resetting the AVR
During reset, all I/O Registers are set to their initial values, and the program starts execution from the Reset Vector. The instruction placed at the Reset Vector must be a JMP - Absolute Jump - instruction to the reset handling routine. If the program never enables an interrupt source, the Interrupt Vectors are not used, and regular program code can be placed at these locations. The circuit diagram in "Reset Logic" on page 43 shows the reset logic. Table 12-1 on page 52 defines the electrical parameters of the reset circuitry. The I/O ports of the AVR are immediately reset to their initial state when a reset source goes active. This does not require any clock source to be running. After all reset sources have gone inactive, a delay counter is invoked, stretching the internal reset. This allows the voltage regulator to reach a stable level before normal operation starts. The time-out period of the delay counter is defined by the user through the SUT Fuses. The different selections for the delay period are presented in "Clock Sources" on page 26.
11.2
Reset Sources
The ATmega16HVB/32HVB has five sources of reset: * The Power-on Reset module generates a Power-on Reset when the Voltage Regulator starts up. * External Reset. The MCU is reset when a low level is present on the RESET pin for longer than the minimum pulse length. * Watchdog Reset. The MCU is reset when the Watchdog Timer period expires and the Watchdog is enabled. * Brown-out Reset. The MCU is reset when VREG is below the Brown-out Reset Threshold, VBOT. See "Brown-out Detection" on page 45. * debugWIRE Reset. In On-chip Debug mode, the debugWIRE resets the MCU when giving the Reset command.
42
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 11-1. Reset Logic
DATA BUS
MCU Status Register (MCUSR)
OCDRF
Brown-out Detection Power-on Reset Circuit/ Charger Detect POR Reset Circuit debugWIRE Watchdog Timer
VFET
BATT VREG Pull-up Resistor RESET /dW
SPIKE FILTER
Ultra Low Power RC Oscillator
Delay Counters
EXTRF WDRF BODRF
COUNTER RESET
PORF
VREG
TIMEOUT
Clock Generator SUT[1:0]
CK
11.2.1
Power-on Reset and Charger Connect The Voltage Regulator will not start up until the Charger Detect module has enabled it. Before this happens the chip will be in Power-off mode and only the Charger Detect module is enabled. In order for the Charger Detect module to enable the Voltage Regulator, the voltage at the BATT pin must exceed the Power-On Threshold Voltage, VPOT. When the voltage at the BATT pin exceeds VPOT, the Voltage Regulator starts up and the chip enters RESET mode. When the Delay Counter times out, the chip will enter Active mode. See Figure 10-1 on page 36. For details on Charger Detect, see "Charger Detect" on page 129.
43
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 11-2. Powering up ATmega16HVB/32HVB
V BATT V POT
V REG 3.3 V
POR
INTERNAL_RESET
t TOUT
SLEEP_MODE
Power-off
Reset
Active
11.2.2
External Reset An External Reset is generated by a low level on the RESET pin. Reset pulses longer than the minimum pulse width (see Table 32-3 on page 230) will generate a reset, even if the clock is not running. Shorter pulses are not guaranteed to generate a reset. When the applied signal reaches the Reset Threshold Voltage - VRST - on its positive edge, the delay counter starts the MCU after the Time-out period - tTOUT - has expired. Figure 11-3. External Reset During Operation
11.2.3
Watchdog Reset When the Watchdog times out, it will generate a short reset pulse of one CK cycle duration. On the falling edge of this pulse, the delay timer starts counting the Time-out period tTOUT. Refer to page 46 for details on operation of the Watchdog Timer.
44
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 11-4. Watchdog Reset During Operation
FET
CK
11.2.4
Brown-out Detection ATmega16HVB/32HVB has an On-chip Brown-out Detection (BOD) circuit for monitoring the VCC level during operation by comparing it to a fixed trigger level VBOT. The trigger level has a hysteresis to ensure spike free Brown-out Detection. The hysteresis on the detection level should be interpreted as VBOT+ = VBOT + VHYST/2 and VBOT- = VBOT - VHYST/2. The BOD is automatically enabled in all modes of operation, except in Power-off mode. When the BOD is enabled, and VCC decreases to a value below the trigger level (VBOT- in Figure 11-5), the Brown-out Reset is immediately activated. When VCC increases above the trigger level (VBOT+ in Figure 11-5), the delay counter starts the MCU after the Time-out period tTOUT has expired. Figure 11-5. Brown-out Reset During Operation
VCC VBOTVBOT+
RESET
TIME-OUT
tTOUT
INTERNAL RESET
11.3
Reset and the Voltage Reference
The Voltage Reference is important for the performance of the system as the VREF voltage will be used as reference voltage for several modules. It is therefore important to notice that after a reset condition the Voltage Reference needs calibration and settling before the VREF voltage is accurate. For details on Voltage Reference calibration and settling time, See "Voltage Reference and Temperature Sensor" on page 123.
45
8042A-AVR-07/09
ATmega16HVB/32HVB
11.4
11.4.1
Watchdog Timer
Features * Clocked from separate On-chip Oscillator * 3 Operating modes
- Interrupt - System Reset - Interrupt and System Reset * Selectable Time-out period from 16 ms to 8s * Possible Hardware fuse Watchdog always on (WDTON) for fail-safe mode
11.4.2
Overview ATmega16HVB/32HVB has an Enhanced Watchdog Timer (WDT). The WDT counts cycles of the Ultra Low Power RC Oscillator. The WDT gives an interrupt or a system reset when the counter reaches a given time-out value. In normal operation mode, it is required that the system uses the WDR - Watchdog Timer Reset - instruction to restart the counter before the time-out value is reached. If the system doesn't restart the counter, an interrupt or system reset will be issued. Figure 11-6. Watchdog Timer
Ultra Low Power RC OSCILLATOR
16 ms 32 ms 64 ms 0.13s 0.26s 0.51s 1.0s 2.0s 4.1s 8.2s
WATCHDOG RESET WDE
WDP0 WDP1 WDP2 WDP3
MCU RESET
WDIF INTERRUPT
WDIE
In Interrupt mode, the WDT gives an interrupt when the timer expires. This interrupt can be used to wake the device from sleep-modes, and also as a general system timer. One example is to limit the maximum time allowed for certain operations, giving an interrupt when the operation has run longer than expected. In System Reset mode, the WDT gives a reset when the timer expires. This is typically used to prevent system hang-up in case of runaway code. The third mode, Interrupt and System Reset mode, combines the other two modes by first giving an interrupt and then switch to System Reset mode. This mode will for instance allow a safe shutdown by saving critical parameters before a system reset. The Watchdog always on (WDTON) fuse, if programmed, will force the Watchdog Timer to System Reset mode. With the fuse programmed the System Reset mode bit (WDE) and Interrupt mode bit (WDIE) are locked to 1 and 0 respectively. To further ensure program security, alterations to the Watchdog set-up must follow timed sequences. The sequence for clearing WDE and changing time-out configuration is as follows:
46
8042A-AVR-07/09
ATmega16HVB/32HVB
1. In the same operation, write a logic one to the Watchdog change enable bit (WDCE) and WDE. A logic one must be written to WDE regardless of the previous value of the WDE bit. 2. Within the next four clock cycles, write the WDE and Watchdog prescaler bits (WDP) as desired, but with the WDCE bit cleared. This must be done in one operation. The following code example shows one assembly and one C function for turning off the Watchdog Timer. The example assumes that interrupts are controlled (e.g. by disabling interrupts globally) so that no interrupts will occur during the execution of these functions. Assembly Code Example(1)
WDT_off: ; Turn off global interrupt cli ; Reset Watchdog Timer wdr ; Clear WDRF in MCUSR in andi out r16, MCUSR r16, (0xff & (0<; Write logical one to WDCE and WDE ; Keep old prescaler setting to prevent unintentional time-out in ori out ldi out sei ret r16, WDTCSR r16, (1<; Turn off WDT
; Turn on global interrupt
C Code Example(1)
void WDT_off(void) { __disable_interrupt(); __watchdog_reset(); /* Clear WDRF in MCUSR */ MCUSR &= ~(1<47
8042A-AVR-07/09
ATmega16HVB/32HVB
Note: If the Watchdog is accidentally enabled, for example by a runaway pointer or brown-out condition, the device will be reset and the Watchdog Timer will stay enabled. If the code is not set up to handle the Watchdog, this might lead to an eternal loop of time-out resets. To avoid this situation, the application software should always clear the Watchdog System Reset Flag (WDRF) and the WDE control bit in the initialization routine, even if the Watchdog is not in use. The following code example shows one assembly and one C function for changing the time-out value of the Watchdog Timer.
Assembly Code Example(1)
WDT_Prescaler_Change: ; Turn off global interrupt cli ; Reset Watchdog Timer wdr ; Start timed sequence in ori out ; -ldi out ; -sei ret r16, WDTCSR r16, (1<; Set new prescaler(time-out) value = 64K cycles (~0.5 s)
; Turn on global interrupt
C Code Example(1)
void WDT_Prescaler_Change(void) { __disable_interrupt(); __watchdog_reset(); /* Start timed equence */ WDTCSR |= (1<Note: The Watchdog Timer should be reset before any change of the WDP bits, since a change in the WDP bits can result in a time-out when switching to a shorter time-out period.
48
8042A-AVR-07/09
ATmega16HVB/32HVB
11.5
11.5.1
Register Description
MCUSR - MCU Status Register The MCU Status Register provides information on which reset source caused an MCU reset.
Bit 0x34 (0x54) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 OCDRF R/W 3 WDRF R/W 2 BODRF R/W See Bit Description 1 EXTRF R/W 0 PORF R/W MCUSR
* Bits 7:5 - Res: Reserved Bits These bits are reserved bits in the ATmega16HVB/32HVB, and will always read as zero. * Bit 4 - OCDRF: OCD Reset Flag This bit is set if a debugWIRE Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 3 - WDRF: Watchdog Reset Flag This bit is set if a Watchdog Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 2 - BODRF: Brown-out Reset Flag This bit is set if a Brown-out Reset occurs. In the case of a Power-on Reset, both the BODRF and the PORF will be set. The BODRF is reset by writing a logic zero to the flag. * Bit 1 - EXTRF: External Reset Flag This bit is set if an External Reset occurs. The bit is reset by a Power-on Reset, or by writing a logic zero to the flag. * Bit 0 - PORF: Power-on Reset Flag This bit is set if a Power-on Reset occurs. The bit is reset only by writing a logic zero to the flag. To make use of the Reset flags to identify a reset condition, the user should read and then reset the MCUSR as early as possible in the program. If the register is cleared before another reset occurs, the source of the reset can be found by examining the reset flags. 11.5.2 WDTCSR - Watchdog Timer Control Register
Bit (0x60) Read/Write Initial Value 7 WDIF R/W 0 6 WDIE R/W 0 5 WDP3 R/W 0 4 WDCE R/W 0 3 WDE R/W X 2 WDP2 R/W 0 1 WDP1 R/W 0 0 WDP0 R/W 0 WDTCSR
* Bit 7 - WDIF: Watchdog Interrupt Flag This bit is set when a time-out occurs in the Watchdog Timer and the Watchdog Timer is configured for interrupt. WDIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, WDIF is cleared by writing a logic one to the flag. When the I-bit in SREG and WDIE are set, the Watchdog Time-out Interrupt is executed.
49
8042A-AVR-07/09
ATmega16HVB/32HVB
* Bit 6 - WDIE: Watchdog Interrupt Enable When this bit is written to one and the I-bit in the Status Register is set, the Watchdog Interrupt is enabled. If WDE is cleared in combination with this setting, the Watchdog Timer is in Interrupt Mode, and the corresponding interrupt is executed if time-out in the Watchdog Timer occurs. If WDE is set, the Watchdog Timer is in Interrupt and System Reset Mode. The first time-out in the Watchdog Timer will set WDIF. Executing the corresponding interrupt vector will clear WDIE and WDIF automatically by hardware (the Watchdog goes to System Reset Mode). This is useful for keeping the Watchdog Timer security while using the interrupt. To stay in Interrupt and System Reset Mode, WDIE must be set after each interrupt. This should however not be done within the interrupt service routine itself, as this might compromise the safety-function of the Watchdog System Reset mode. If the interrupt is not executed before the next time-out, a System Reset will be applied. Table 11-1.
WDTON(1) 1 1 1 1 0 Note:
Watchdog Timer Configuration
WDE 0 0 1 1 x WDIE 0 1 0 1 x Mode Stopped Interrupt Mode System Reset Mode Interrupt and System Reset Mode System Reset Mode Action on Time-out None Interrupt Reset Interrupt, then go to System Reset Mode Reset
1. WDTON Fuse set to "0" means programmed, "1" means unprogrammed.
* Bit 5, 2:0 - WDP3:0 : Watchdog Timer Prescaler 3, 2, 1 and 0 The WDP3..0 bits determine the Watchdog Timer prescaling when the Watchdog Timer is enabled. The different prescaling values and their corresponding Timeout Periods are shown in Table 11-2. * Bit 4 - WDCE: Watchdog Change Enable This bit is used in timed sequences for changing WDE and prescaler bits. To clear the WDE bit, and/or change the prescaler bits, WDCE must be set. Once written to one, hardware will clear WDCE after four clock cycles. * Bit 3 - WDE: Watchdog System Reset Enable WDE is overridden by WDRF in MCUSR. This means that WDE is always set when WDRF is set. To clear WDE, WDRF must be cleared first. This feature ensures multiple resets during conditions causing failure, and a safe start-up after the failure. * Bits 5, 2:0 - WDP3:0: Watchdog Timer Prescaler 3, 2, 1, and 0 The WDP3..0 bits determine the Watchdog Timer prescaling when the Watchdog Timer is enabled. The different prescaling values and their corresponding Timeout Periods are shown in Table 11-2 on page 51.
50
8042A-AVR-07/09
ATmega16HVB/32HVB
. Table 11-2.
WDP3 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1
Watchdog Timer Prescale Select
WDP2 0 0 0 0 1 1 1 1 0 0 0 0 1 1 1 1 WDP1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 WDP0 0 1 0 1 0 1 0 1 0 1 0 1 0 Reserved 1 0 1 Number of WDT Oscillator Cycles 2K cycles 4K cycles 8K cycles 16K cycles 32K cycles 64K cycles 128K cycles 256K cycles 512K cycles 1024K cycles Typical Time-out(1) 16 ms 32 ms 64 ms 0.13s 0.26s 0.51s 1.0s 2.0s 4.1s 8.2s
Note:
1. The actual timeout value depends on the actual clock period of the Ultra Low Power RC Oscillator, refer to "Ultra Low Power RC Oscillator" on page 27" for details.
51
8042A-AVR-07/09
ATmega16HVB/32HVB
12. Interrupts
12.1 Overview
This section describes the specifics of the interrupt handling as performed in ATmega16HVB/32HVB. For a general explanation of the AVR interrupt handling, refer to "Reset and Interrupt Handling" on page 14.
12.2
Interrupt Vectors in ATmega16HVB/32HVB
. Table 12-1.
Vector No. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
Reset and Interrupt Vectors
Program Address(1) Source RESET BPINT VREGMON INT0 INT1 INT2 INT3 PCINT0 PCINT1 WDT BGSCD CHDET TIMER1 IC TIMER1 COMPA TIMER1 COMPB TIMER1 OVF TIMER0 IC TIMER0 COMPA TIMER0 COMPB TIMER0 OVF TWI BUS C/D TWI SPI, STC VADC CCADC CONV CCADC REG CUR Interrupt Definition External Pin, Power-on Reset, Brown-out Reset, Watchdog Reset, and debugWIRE Reset Battery Protection Interrupt Voltage Regulator Monitor Interrupt External Interrupt Request 0 External Interrupt Request 1 External Interrupt Request 2 External interrupt Request 3 Pin Change Interrupt 0 Pin Change Interrupt 1 Watchdog Time-out Interrupt Bandgap Buffer Short Circuit Detected Charger Detect Timer/Counter 1 input Capture Timer/Counter 1 Compare Match A Timer/Counter 1 Compare Match B Timer/Counter 1 Overflow Timer/Counter 0 input Capture Timer/Counter 0 Compare Match A Timer /Counter0 Compare Match B Timer/Counter 0 Overflow Two-wire Bus Connect/Disconnect Two-wire Serial Interface SPI, Serial Transfer Complete Voltage ADC Conversion Complete CC-ADC Instantaneous Current Conversion Complete CC-ADC Regular Current
0x0000 0x0002 0x0004 0x0006 0x0008 0x000A 0x000C 0x000E 0x0010 0x0012 0x0014 0x0016 0x0018 0x001A 0x001C 0x001E 0x0020 0x0022 0x0024 0x0026 0x0028 0x002A 0x002C 0x002E 0x0030 0x0032
52
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 12-1.
Vector No. 27 28 29 Notes:
Reset and Interrupt Vectors (Continued)
Program Address(1) Source CCADC ACC EE READY SPM Interrupt Definition CC-ADC Accumulate Current Conversion Complete EEPROM Ready SPM Ready
0x0034 0x0036 0x0038
1. When the IVSEL bit in MCUCR is set, Interrupt Vectors will be moved to the start of the Boot Flash Section. The address of each Interrupt Vector will then be the address in this table added to the start address of the Boot Flash Section. 2. When the BOOTRST Fuses are programmed, the device will jump to the Boot Loader address at reset, see "Boot Loader Support - Read-While-Write Self-Programming" on page 191.
If the program never enables an interrupt source, the Interrupt Vectors are not used, and regular program code can be placed at these locations. Table 12-2 shows reset and Interrupt Vectors placement for the various combinations of BOOTRST and IVSEL settings. If the program never enables an interrupt source, the Interrupt Vectors are not used, and regular program code can be placed at these locations. This is also the case if the Reset Vector is in the Application section while the Interrupt Vectors are in the Boot section or vice versa. Table 12-2.
BOOTRST 1 1 0 0 Note:
Reset and Interrupt Vectors Placement(1)
IVSEL 0 1 0 1 Reset Address 0x0000 0x0000 Boot Reset Address Boot Reset Address Interrupt Vectors Start Address 0x0002 Boot Reset Address + 0x0002 0x0002 Boot Reset Address + 0x0002
1. The Boot Reset Address is shown in Table 29-5 on page 204. For the BOOTRST Fuse "1" means unprogrammed while "0" means programmed.
The most typical and general program setup for the Reset and Interrupt Vector Addresses in ATmega16HVB/32HVB is:
Address 0x0000 0x0002 0x0004 0x0006 0x0008 0x000A 0x000C 0x000E 0x0010 0x0012 0x0014 0x0016 0x0018 0x001A Labels Code jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp RESET BPINT VREGMON_INT EXT_INT0 EXT_INT1 EXT_INT2 EXT_INT3 PCINT0 PCINT1 WDT BGSCD CHDET TIM1_IC TIM1_COMPA Comments ; Reset Handler ; Battery Protection Interrupt Handler ; Voltage Regulator Monitor Interrupt Handler ; External Interrupt Request 0 Handler ; External Interrupt Request 1 Handler ; External Interrupt Request 2 Handler ; External Interrupt Request 3 Handler ; Pin Change Interrupt 0 Handler ; Pin Change Interrupt 1 Handler ; Watchdog Time-out Interrupt ; Bandgap Buffer Short Circuit Detected ; Charger Detect ; Timer1 Input Capture Handler ; Timer1 Compare A Handler
53
8042A-AVR-07/09
ATmega16HVB/32HVB
0x001C 0x001E 0X0020 0x0022 0x0024 0x0026 0x0028 0x002A 0x002C 0x002E 0x0030 0x0032 0x0034 0x0036 0x0038 ; 0x003A 0x003B 0x003C 0x003D 0x003E 0x003F 0x0040 ; ... RESET: ldi out ldi out sei ... xxx ... r16, high(RAMEND) SPH,r16 r16, low(RAMEND) SPL,r16 ; Enable interrupts ; Main program start ; Set Stack Pointer to top of RAM jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp jmp TIM1_COMPB TIM1_OVF TIM0_IC TIM0_COMPA TIM0_COMPB TIM0_OVF TWI_BUS_CD TWI SPI, STC VADC CCADC_CONV CCADC_REC_CUR CCADC_ACC EE_RDY SPM ; Timer1 Compare B Handler ; Timer1 Overflow Handler ; Timer0 Input Capture Handler ; Timer0 CompareA Handler ; Timer0 CompareB Handler ; Timer0 Overflow Handler ; Two-wire Bus Connect/Disconnect Handler ; Two-wire Serial Interface Handler ; SPI, Serial Transfer Complete ; Voltage ADC Conversion Complete Handler ; CC-ADC Instantaneous Current Conversion Complete Handler ; CC-ADC Regular Current Handler ; CC-ADC Accumulate Current Conversion Complete Handler ; EEPROM Ready Handler ; Store Program Memory Ready Handler
When the BOOTRST Fuse is unprogrammed, the Boot section size set to 4K bytes and the IVSEL bit in the MCUCR Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector Addresses is:
Address Labels 0x0000 0x0001 0x0002 0x0003 0x0004 0x0005 ; .org 0x4C02 0x4C02 0x4C04 ... 0x4C2C jmp jmp ... jmp BPINT EXT_INT0 ... SPM_RDY ; Battery Protection Interrupt Handler ; External Interrupt Request 0 Handler ; ; Store Program Memory Ready Handler RESET: Code ldi out ldi out sei SPH,r16 r16,low(RAMEND) SPL,r16 ; Enable interrupts xxx Comments r16,high(RAMEND); Main program start ; Set Stack Pointer to top of RAM
When the BOOTRST Fuse is programmed and the Boot section size set to 4K bytes, the most typical and general program setup for the Reset and Interrupt Vector Addresses is:
Address Labels .org 0x0002 0x0002 0x0004 jmp jmp BPINT EXT_INT0 ; Battery Protection Interrupt Handler ; External Interrupt Request 0 Handler Code Comments
54
8042A-AVR-07/09
ATmega16HVB/32HVB
... 0x002C ; .org 0x4C00 0x4C00 RESET: 0x4C01 0x4C02 0x4C03 0x4C04 0x4C05 ldi out ldi out sei r16,high(RAMEND); Main program start SPH,r16 r16,low(RAMEND) SPL,r16 ; Enable interrupts xxx ; Set Stack Pointer to top of RAM jmp ... ... SPM_RDY ; ; Store Program Memory Ready Handler
When the BOOTRST Fuse is programmed, the Boot section size set to 4K bytes and the IVSEL bit in the MCUCR Register is set before any interrupts are enabled, the most typical and general program setup for the Reset and Interrupt Vector Addresses is:
Address Labels Code ; .org 0x4C00 0x4C00 0x4C02 0x4C04 ... 0x4C2C ; 0x4C2E 0x4C2F 0x4C30 0x4C31 0x4C32 0x4C33 RESET: ldi out ldi out sei r16,high(RAMEND); Main program start SPH,r16 r16,low(RAMEND) SPL,r16 ; Enable interrupts xxx ; Set Stack Pointer to top of RAM jmp jmp jmp ... jmp RESET BPINT EXT_INT0 ... SPM_RDY ; Reset handler ; Battery Protection Interrupt Handler ; External Interrupt Request 0 Handler ; ; Store Program Memory Ready Handler Comments
55
8042A-AVR-07/09
ATmega16HVB/32HVB
12.3
Moving Interrupts Between Application and Boot Space
The General Interrupt Control Register controls the placement of the Interrupt Vector table.
Assembly Code Example
Move_interrupts: ; Enable change of Interrupt Vectors ldi r16, (1<C Code Example
void Move_interrupts(void) { /* Enable change of Interrupt Vectors */ MCUCR = (1<12.4
12.4.1
Register Description
MCUCR - MCU Control Register
Bit 0x35 (0x55) Read/Write Initial Value 7 JTD R/W 0 6 - R 0 5 - R 0 4 PUD R/W 0 3 - R 0 2 - R 0 1 IVSEL R/W 0 0 IVCE R/W 0 MCUCR
* Bit 1 - IVSEL: Interrupt Vector Select When the IVSEL bit is cleared (zero), the Interrupt Vectors are placed at the start of the Flash memory. When this bit is set (one), the Interrupt Vectors are moved to the beginning of the Boot Loader section of the Flash. The actual address of the start of the Boot Flash Section is determined by the BOOTSZ Fuses. Refer to the section "Boot Loader Support - Read-While-Write Self-Programming" on page 191 for details. To avoid unintentional changes of Interrupt Vector tables, a special write procedure must be followed to change the IVSEL bit: a. Write the Interrupt Vector Change Enable (IVCE) bit to one. b. Within four cycles, write the desired value to IVSEL while writing a zero to IVCE.
Interrupts will automatically be disabled while this sequence is executed. Interrupts are disabled in the cycle IVCE is set, and they remain disabled until after the instruction following the write to
56
8042A-AVR-07/09
ATmega16HVB/32HVB
IVSEL. If IVSEL is not written, interrupts remain disabled for four cycles. The I-bit in the Status Register is unaffected by the automatic disabling.
Note: If Interrupt Vectors are placed in the Boot Loader section and Boot Lock bit BLB02 is programmed, interrupts are disabled while executing from the Application section. If Interrupt Vectors are placed in the Application section and Boot Lock bit BLB12 is programed, interrupts are disabled while executing from the Boot Loader section. Refer to the section "Boot Loader Support - Read-WhileWrite Self-Programming" on page 191 for details on Boot Lock bits.
* Bit 0 - IVCE: Interrupt Vector Change Enable The IVCE bit must be written to logic one to enable change of the IVSEL bit. IVCE is cleared by hardware four cycles after it is written or when IVSEL is written. Setting the IVCE bit will disable interrupts, as explained in the IVSEL description above. See Code Example below.
57
8042A-AVR-07/09
ATmega16HVB/32HVB
13. External Interrupts
13.1 Overview
The External Interrupts are triggered by the INT3:0 pin or any of the PCINT11:0 pins. Observe that, if enabled, the interrupts will trigger even if the INT3:0 or PCINT11:0 pins are configured as outputs. This feature provides a way of generating a software interrupt. The External Interrupts can be triggered by a falling or rising edge or a low level. This is set up as indicated in the specification for the "EICRA - External Interrupt Control Register A" on page 58. When the external interrupt is enabled and is configured as level triggered, the interrupt will trigger as long as the pin is held low. Interrupts are detected asynchronously. This implies that these interrupts can be used for waking the part also from sleep modes other than Idle mode. The I/O clock is halted in all sleep modes except Idle mode. The Pin change interrupt PCI1 will trigger if any enabled PCINT11:4 pin toggles and Pin change interrupts PCI0 will trigger if any enabled PCINT3:0 pin toggles. PCMSK1 and PCMSK0 Registers control which pins contribute to the pin change interrupts. Pin change interrupts on PCINT11:0 are detected asynchronously. This implies that these interrupts can be used for waking the part also from sleep modes other than Idle mode. Note that if a level triggered interrupt is used for wake-up from Power-save, the required level must be held long enough for the MCU to complete the wake-up to trigger the level interrupt. If the level disappears before the end of the Start-up Time, the MCU will still wake up, but no interrupt will be generated. The start-up time is defined by the SUT fuses as described in "Clock Systems and their Distribution" on page 25.
13.2
13.2.1
Register Description
EICRA - External Interrupt Control Register A
Bit (0x69) Read/Write Initial Value 7 ISC31 R/W 0 6 ISC30 R/W 0 5 ISC21 R/W 0 4 ISC20 R/W 0 3 ISC11 R/W 0 2 ISC10 R/W 0 1 ISC01 R/W 0 0 ISC00 R/W 0 EICRA
* Bits 7:0 - ISCn: External Interrupt Sense Control Bits The External Interrupts 3:0 are activated by the external pins INT3:0 if the SREG I-flag and the corresponding interrupt mask in the EIMSK is set. The level and edges on the external pins that activate the interrupts are defined in Table 13-1 on page 59. Edges on INT3..INT0 are registered asynchronously. Pulses on INT3:0 pins wider than the minimum pulse width given in Table 3211 on page 233 will generate an interrupt. Shorter pulses are not guaranteed to generate an interrupt. If low level interrupt is selected, the low level must be held until the completion of the currently executing instruction to generate an interrupt. If enabled, a level triggered interrupt will generate an interrupt request as long as the pin is held low. When changing the ISCn bit, an interrupt can occur. Therefore, it is recommended to first disable INTn by clearing its Interrupt Enable bit in the EIMSK Register. Then, the ISCn bit can be changed. Finally, the INTn interrupt flag should be cleared by writing a logical one to its Interrupt Flag bit (INTFn) in the EIFR Register before the interrupt is re-enabled.
58
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 13-1.
ISCn1 0 0 1 1 Note:
Interrupt Sense Control
ISCn0 0 1 0 1 Description The low level of INTn generates an interrupt request. Any logical change on INTn generates an interrupt request. The falling edge of INTn generates an interrupt request. The rising edge of INTn generates an interrupt request.
1. n = 3, 2, 1, or 0. When changing the ISCn1/ISCn0 bits, the interrupt must be disabled by clearing its Interrupt Enable bit in the EIMSK Register. Otherwise an interrupt can occur when the bits are changed.
13.2.2
EIMSK - External Interrupt Mask Register
Bit 0x1D (0x3D) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 INT3 R/W 0 2 INT2 R/W 0 1 INT1 R/W 0 0 INT0 R/W 0 EIMSK
* Bits 7:4 - RES: Reserved Bits These bits are reserved bits ins the ATmega16HVB/32HVB, and will always read as zero. * Bits 3:0 - INT3 - INT0: External Interrupt Request 3:0 Enable When an INT3 - INT0 bit is written to one and the I-bit in the Status Register (SREG) is set (one), the corresponding external pin interrupt is enabled. The Interrupt Sense Control bits in the External Interrupt Control Register - EICRA - defines whether the external interrupt is activated on rising or falling edge or level sensed. Activity on any of these pins will trigger an interrupt request even if the pin is enabled as an output. This provides a way of generating a software interrupt. 13.2.3 EIFR - External Interrupt Flag Register
Bit 0x1C (0x3C) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 INTF3 R/W 0 2 INTF2 R/W 0 1 INTF1 R/W 0 0 INTF0 R/W 0 EIFR
* Bits 7:4 - RES: Reserved Bits These bits are reserved bits ins the ATmega16HVB/32HVB, and will always read as zero. * Bits 3:0 - INTF3 - INTF0: External Interrupt Flags 3:0 When an edge or logic change on the INT3:0 pin triggers an interrupt request, INTF3:0 becomes set (one). If the I-bit in SREG and the corresponding interrupt enable bit, INT3:0 in EIMSK, are set (one), the MCU will jump to the interrupt vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. These flags are always cleared when INT3:0 are configured as level interrupt. Note that when entering sleep mode with the INT3:0 interrupts disabled, the input buffers on these pins will be disabled. This may cause a logic change in internal signals which will set the INTF3:0 flags. See "Digital Input Enable and Sleep Modes" on page 71 for more information.
59
8042A-AVR-07/09
ATmega16HVB/32HVB
13.2.4 PCICR - Pin Change Interrupt Control Register
Bit (0x68) Read/Write Initial Value 7 R 0 6 R 0 5 R 0 4 R 0 3 R 0 2 R 0 1 PCIE1 R/W 0 0 PCIE0 R/W 0 PCICR
* Bits 7:2 - RES: Reserved Bits These bits are reserved bits ins the ATmega16HVB/32HVB, and will always read as zero. * Bit 1 - PCIE1: Pin Change Interrupt Enable 1 When the PCIE1 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt 1 is enabled. Any change on any enabled PCINT11..4 pin will cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI1 Interrupt Vector. PCINT11..4 pins are enabled individually by the PCMSK1 Register. * Bit 0 - PCIE0: Pin Change Interrupt Enable 0 When the PCIE0 bit is set (one) and the I-bit in the Status Register (SREG) is set (one), pin change interrupt 0 is enabled. Any change on any enabled PCINT3..0 pin will cause an interrupt. The corresponding interrupt of Pin Change Interrupt Request is executed from the PCI0 Interrupt Vector. PCINT3..0 pins are enabled individually by the PCMSK0 Register. 13.2.5 PCIFR - Pin Change Interrupt Flag Register
Bit 0x1B (0x3B) Read/Write Initial Value 7 R 0 6 R 0 5 R 0 4 R 0 3 R 0 2 R 0 1 PCIF1 R/W 0 0 PCIF0 R/W 0 PCIFR
* Bits 7:2 - RES: Reserved Bits These bits are reserved bits ins the ATmega16HVB/32HVB, and will always read as zero. * Bit 1 - PCIF1: Pin Change Interrupt Flag 1 When a logic change on any PCINT11..4 pin triggers an interrupt request, PCIF1 becomes set (one). If the I-bit in SREG and the PCIE1 bit in EIMSK are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. * Bit 0 - PCIF0: Pin Change Interrupt Flag 0 When a logic change on any PCINT3:0 pin triggers an interrupt request, PCIF0 becomes set (one). If the I-bit in SREG and the PCIE0 bit in EIMSK are set (one), the MCU will jump to the corresponding Interrupt Vector. The flag is cleared when the interrupt routine is executed. Alternatively, the flag can be cleared by writing a logical one to it. 13.2.6 PCMSK1 - Pin Change Mask Register 1
Bit (0x6C) Read/Write Initial Value 7
PCINT11
6
PCINT10
5
PCINT9
4
PCINT8
3
PCINT7
2
PCINT6
1
PCINT5
0
PCINT4 PCMSK1
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
60
8042A-AVR-07/09
ATmega16HVB/32HVB
* Bit 7:0 - PCINT11:4: Pin Change Enable Mask 15..8 These bits select whether pin change interrupt is enabled on the corresponding I/O pin. If PCINT11:4 is set and the PCIE1 bit in EIMSK is set, pin change interrupt is enabled on the corresponding I/O pin. If PCINT11:4 is cleared, pin change interrupt on the corresponding I/O pin is disabled. 13.2.7 PCMSK0 - Pin Change Mask Register 0
Bit (0x6B) Read/Write Initial Value 7 R 0 6 R 0 5 R 0 4 R 0 3 PCINT3 R/W 0 2 PCINT2 R/W 0 1 PCINT1 R/W 0 0 PCINT0 R/W 0 PCMSK0
* Bits 7:4 - RES: Reserved Bits These bits are reserved bits ins the ATmega16HVB/32HVB, and will always read as zero. * Bit 3:0 - PCINT3:0: Pin Change Enable Mask 3:0 Each PCINT3:0 bit selects whether pin change interrupt is enabled on the corresponding I/O pin. If PCINT3:0 is set and the PCIE0 bit in PCICR is set, pin change interrupt is enabled on the corresponding I/O pin. If PCINT3:0 is cleared, pin change interrupt on the corresponding I/O pin is disabled.
61
8042A-AVR-07/09
ATmega16HVB/32HVB
14. High Voltage I/O Ports
14.1 Overview
All high voltage AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports. This means that the state of one port pin can be changed without unintentionally changing the state of any other pin with the SBI and CBI instructions. All high voltage I/O pins have protection Zener diodes to Ground as indicated in Figure 14-1. See "Electrical Characteristics" on page 228 for a complete list of parameters. Figure 14-1. High Voltage I/O Pin Equivalent Schematic
Pxn
Logic Cpin
See Figure "General High Voltage Digital I/O" for Details
All registers and bit references in this section are written in general form. A lower case "x" represents the numbering letter for the port, and a lower case "n" represents the bit number. However, when using the register or bit defines in a program, the precise form must be used. For example, PORTC3 for bit number three in Port C, here documented generally as PORTxn. The physical I/O Registers and bit locations are listed in "Register Description" on page 66. One I/O Memory address location is allocated for each high voltage port, the Data Register - PORTx. The Data Register is read/write. Using the I/O port as General Digital Output is described in "High Voltage Ports as General Digital I/O" on page 63.
62
8042A-AVR-07/09
ATmega16HVB/32HVB
14.2 High Voltage Ports as General Digital I/O
The high voltage ports are high voltage tolerant open collector output ports. In addition they can be used as general digital inputs. Figure 14-2 shows a functional description of one output port pin, here generically called Pxn. Figure 14-2. General High Voltage Digital I/O(1)
Pxn
Q
D
PORTxn _ Q
CLR
RESET
WRx RRx
SLEEP
SYNCHRONIZER
D
SET
RPx
D Q
Q _ Q
L
CLR
PINxn _ CLR Q
clkI/O
HIGH VOLTAGE DIGITAL INPUT (2)
SLEEP: clkI/O: SLEEP CONTROL I/O CLOCK RRx: WRx: RPx: READ PORTx REGISTER WRITE PORTx REGISTER READ PINx REGISTER
Notes:
1. WRx, RRx and RPx are common to all pins within the same port. clkI/O and SLEEP are common to all ports. 2. The High Voltage Digital Input is not present on PC5.
14.2.1
Configuring the Pin Each port pin consist of two register bits: PORTxn and PINxn. As shown in "Register Description" on page 66, the PORTxn bits are accesed at the PORTx I/O address, and the PINxn bits at the PINx I/O address. If PORTxn is written logic one, the port pin is driven low (zero). If PORTxn is written logic zero, the port pin is tri-stated. The port pins are tri-stated when a reset condition becomes active, even if no clocks are running.
14.2.2
Reading the Pin The port pin can be read through the PINxn Register bit. As shown in Figure 14-2, the PINxn Register bit and the preceding latch constitute a synchronizer. This is needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces a delay.
DATABUS
63
8042A-AVR-07/09
ATmega16HVB/32HVB
14.3 14.4 Overview Alternate Port Functions
The High Voltage I/O has alternate port functions in addition to being general digital I/O. Figure 14-3 shows how the port pin control signals from the simplified Figure 14-2 on page 63 can be overridden by alternate functions. Figure 14-3. High Voltage Digital I/O(1)(2)
Pxn
PVOExn
1 0
PVOVxn
Q D PORTxn _ Q
CLR
DIEOExn DIEOVxn
1 0
RESET
WRx
SLEEP
SYNCHRONIZER
D
SET
RPx
D Q
Q _ Q
L
CLR
PINxn _ CLR Q
clkI/O
DIxn
PVOExn: PVOVxn: DIEOExn: DIEOVxn:
Pxn PORT VALUE OVERRIDE ENABLE Pxn PORT VALUE OVERRIDE VALUE Pxn DIGITAL INPUT-ENABLE OVERRIDE ENABLE Pxn DIGITAL INPUT-ENABLE OVERRIDE VALUE
RRx: WRx: RPx: clkI/O: DIxn: SLEEP:
READ PORTx REGISTER WRITE PORTx REGISTER READ PINx REGISTER I/O CLOCK DIGITAL INPUT PIN n ON PORTx SLEEP CONTROL
Notes:
1. WRx, RRx and RPx are common to all pins within the same port. clkI/O and SLEEP are common to all ports. All other signals are unique for each pin. 2. The High Voltage Digital Input is not present on PC5.
Table 14-1 on page 65 summarizes the function of the overriding signals. The pin and port indexes from Figure 14-3 are not shown in the succeeding tables. The overriding signals are generated internally in the modules having the alternate function.
DATABUS
RRx
64
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 14-1.
Signal Name
Generic Description of Overriding Signals for Alternate Functions
Full Name Port Value Override Enable Port Value Override Value Digital Input Enable Override Enable Digital Input Enable Override Value Description If this signal is set and the Output Driver is enabled, the port value is controlled by the PVOV signal. If PVOE is cleared, and the Output Driver is enabled, the port Value is controlled by the PORTxn Register bit. If PVOE is set, the port value is set to PVOV, regardless of the setting of the PORTxn Register bit. If this bit is set, the Digital Input Enable is controlled by the DIEOV signal. If this signal is cleared, the Digital Input Enable is determined by MCU state (Normal mode, sleep mode). If DIEOE is set, the Digital Input is enabled/disabled when DIEOV is set/cleared, regardless of the MCU state (Normal mode, sleep mode). This is the Digital Input to alternate functions. In the figure, the signal is connected to the output of the schmitt trigger but before the synchronizer. Unless the Digital Input is used as a clock source, the module with the alternate function will use its own synchronizer.
PVOE
PVOV
DIEOE
DIEOV
DI
Digital Input
14.4.1
Alternate Functions of Port C The Port C pins with alternate functions are shown in Table 14-2. Table 14-2.
Port Pin PC0 PC1 PC2 PC3 PC4
Port C Pins Alternate Functions
Alternate Function INT0/ EXTPROT(External Interrupt 0 or External Battery Protection Input) INT1 (External interrupt 1) INT1 (External interrupt 2) INT3/ SDA (External Interrupt 3 or SM Bus Data line) SCL (SM Bus Clock line)
The alternate pin configuration is as follows: * INT0/ EXTPROT - Port C, Bit 0 INT0: External Interrupt Source 0. This pin can serve as external interrupt source. INT0 can be used as an interrupt pin regardless of whether another function is enabled or not. EXTPROT: External Battery Protection Input. This pin can serve as external battery protection input to be able to override the FET controller externally. * INT1 - Port C, Bit1 INT1: External Interrupt Source 1. This pin can serve as external interrupt source. INT1 can be used as an interrupt pin regardless of whether another function is enabled or not. * INT2 - Port C, Bit2 INT2: External Interrupt Source 2. This pin can serve as external interrupt source. INT2 can be used as an interrupt pin regardless of whether another function is enabled or not.
65
8042A-AVR-07/09
ATmega16HVB/32HVB
* INT3/ SDA - Port C, Bit3 INT3: External Interrupt Source 3. This pin can serve as external interrupt source. INT3 can be used as an interrupt pin regardless of whether another function is enabled or not. SDA: SM Bus Data. This pin can serve as bidirectional serial data line for the 2-wire Serial Interface. * SCL - Port C, Bit4 SCL: SM Bus Clock. This pin can serve as bidirectional clock line for the 2-wire Serial Interface
Table 14-3 on page 66 relates the alternate functions of Port C to the overriding signals shown in Figure 14-3 on page 64. Table 14-3.
Signal Name PVOE PVOV DIEOE DIEOV DI DIDR
Overriding Signals for Alternate Functions in PC4:0
PC4/SCL SM BUS ENABLED SM BUS CLOCK SM BUS ENABLED 1 SM BUS CLOCK PC3/INT3/SDA SM BUS ENABLED SM BUS DATA INT3 ENABLE SM BUS ENABLED 1 INT3 INPUT SM BUS DATA INT2 ENABLE 1 INT2 INPUT INT1ENABLE 1 INT1 INPUT PC2/INT2 PC1/INT1 PC0/INT0/EXTPROT EXTPROT ENABLE 1 INT0 ENABLE EXTPROT ENABLE 1 INT0 INPUT EXTPROT INPUT
14.5
14.5.1
Register Description
PORTC - Port C Data Register
Bit 0x08 (0x28) Read/Write Initial Value 7
-
6
-
5
PORTC5
4
PORTC4
3
PORTC3
2
PORTC2
1
PORTC1
0
PORTC0 PORTC
R 0
R 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
14.5.2
PINC - Port C Input Pins Address
Bit 0x06 (0x26) Read/Write Initial Value 7
-
6
-
5 R N/A
4 PINC4 R N/A
3 PINC3 R N/A
2 PINC2 R N/A
1 PINC1 R N/A
0 PINC0 R N/A PINC
R N/A
R N/A
66
8042A-AVR-07/09
ATmega16HVB/32HVB
15. Low Voltage I/O-Ports
15.1 Overview
All low voltage AVR ports have true Read-Modify-Write functionality when used as general digital I/O ports. This means that the direction of one port pin can be changed without unintentionally changing the direction of any other pin with the SBI and CBI instructions. The same applies when changing drive value (if configured as output) or enabling/disabling of pull-up resistors (if configured as input). All low voltage port pins have individually selectable pull-up resistors with a supply-voltage invariant resistance. All I/O pins have protection diodes to both VREG and Ground as indicated in Figure 15-1. Refer to "Electrical Characteristics" on page 228 for a complete list of parameters. Figure 15-1. Low Voltage I/O Pin Equivalent Schematic
Rpu
Pxn
Logic Cpin
See Figure "General Digital I/O" for Details
All registers and bit references in this section are written in general form. A lower case "x" represents the numbering letter for the port, and a lower case "n" represents the bit number. However, when using the register or bit defines in a program, the precise form must be used. For example, PORTB3 for bit no. 3 in Port B, here documented generally as PORTxn. The physical I/O Registers and bit locations are listed in "Register Description" on page 78. Three I/O memory address locations are allocated for each low voltage port, one each for the Data Register - PORTx, Data Direction Register - DDRx, and the Port Input Pins - PINx. The Port Input Pins I/O location is read only, while the Data Register and the Data Direction Register are read/write. However, writing a logic one to a bit in the PINx Register, will result in a toggle in the corresponding bit in the Data Register. In addition, the Pull-up Disable - PUD bit in MCUCR disables the pull-up function for all low voltage pins in all ports when set. Using the I/O port as General Digital I/O is described in "Low Voltage Ports as General Digital I/O" on page 68. Many low voltage port pins are multiplexed with alternate functions for the peripheral features on the device. How each alternate function interferes with the port pin is described in "Alternate Port Functions" on page 72. Refer to the individual module sections for a full description of the alternate functions.
67
8042A-AVR-07/09
ATmega16HVB/32HVB
Note that enabling the alternate function of some of the port pins does not affect the use of the other pins in the port as general digital I/O.
15.2
Low Voltage Ports as General Digital I/O
The low voltage ports are bi-directional I/O ports with optional internal pull-ups. Figure 15-2 shows a functional description of one I/O-port pin, here generically called Pxn. Figure 15-2. General Low Voltage Digital I/O(1)
PUD
Q
D
DDxn Q CLR
RESET
WDx RDx
1 Pxn
Q D PORTxn Q CLR
0
WPx RESET WRx SLEEP RRx
SYNCHRONIZER
D Q D Q
RPx
PINxn L Q Q
clk I/O
PUD: SLEEP: clkI/O:
PULLUP DISABLE SLEEP CONTROL I/O CLOCK
WDx: RDx: WRx: RRx: RPx: WPx:
WRITE DDRx READ DDRx WRITE PORTx READ PORTx REGISTER READ PORTx PIN WRITE PINx REGISTER
Note:
1. WRx, WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O, SLEEP, and PUD are common to all ports.
15.2.1
Configuring the Pin Each port pin consists of three register bits: DDxn, PORTxn, and PINxn. As shown in "Register Description" on page 78, the DDxn bits are accessed at the DDRx I/O address, the PORTxn bits at the PORTx I/O address, and the PINxn bits at the PINx I/O address. The DDxn bit in the DDRx Register selects the direction of this pin. If DDxn is written logic one, Pxn is configured as an output pin. If DDxn is written logic zero, Pxn is configured as an input pin. If PORTxn is written logic one when the pin is configured as an input pin, the pull-up resistor is activated. To switch the pull-up resistor off, PORTxn has to be written logic zero or the pin has to be configured as an output pin. The port pins are tri-stated when reset condition becomes active, even if no clocks are running.
DATA BUS
68
8042A-AVR-07/09
ATmega16HVB/32HVB
If PORTxn is written logic one when the pin is configured as an output pin, the port pin is driven high (one). If PORTxn is written logic zero when the pin is configured as an output pin, the port pin is driven low (zero). 15.2.2 Toggling the Pin Writing a logic one to PINxn toggles the value of PORTxn, independent on the value of DDRxn. Note that the SBI instruction can be used to toggle one single bit in a port. 15.2.3 Switching Between Input and Output When switching between tri-state ({DDxn, PORTxn} = 0b00) and output high ({DDxn, PORTxn} = 0b11), an intermediate state with either pull-up enabled {DDxn, PORTxn} = 0b01) or output low ({DDxn, PORTxn} = 0b10) must occur. Normally, the pull-up enabled state is fully acceptable, as a high-impedant environment will not notice the difference between a strong high driver and a pull-up. If this is not the case, the PUD bit in the MCUCR Register can be set to disable all pull-ups in all ports. Switching between input with pull-up and output low generates the same problem. The user must use either the tri-state ({DDxn, PORTxn} = 0b00) or the output high state ({DDxn, PORTxn} = 0b11) as an intermediate step. Table 15-1 summarizes the control signals for the pin value. Table 15-1.
DDxn 0 0 0 1 1
Port Pin Configurations
PUD (in MCUCR) X 0 1 X X I/O Input Input Input Output Output Pull-up No Yes No No No Comment Tri-state (Hi-Z) Pxn will source current if ext. pulled low. Tri-state (Hi-Z) Output Low (Sink) Output High (Source)
PORTxn 0 1 1 0 1
15.2.4
Reading the Pin Value Independent of the setting of Data Direction bit DDxn, the port pin can be read through the PINxn Register bit. As shown in Figure 15-2, the PINxn Register bit and the preceding latch constitute a synchronizer. This is needed to avoid metastability if the physical pin changes value near the edge of the internal clock, but it also introduces a delay. Figure 15-3 shows a timing diagram of the synchronization when reading an externally applied pin value. The maximum and minimum propagation delays are denoted tpd,max and tpd,min respectively.
69
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 15-3. Synchronization when Reading an Externally Applied Pin value
SYSTEM CLK INSTRUCTIONS SYNC LATCH PINxn r17
0x00 t pd, max t pd, min 0xFF XXX XXX in r17, PINx
Consider the clock period starting shortly after the first falling edge of the system clock. The latch is closed when the clock is low, and goes transparent when the clock is high, as indicated by the shaded region of the "SYNC LATCH" signal. The signal value is latched when the system clock goes low. It is clocked into the PINxn Register at the succeeding positive clock edge. As indicated by the two arrows tpd,max and tpd,min, a single signal transition on the pin will be delayed between 1/2 and 11/2 system clock period depending upon the time of assertion. When reading back a software assigned pin value, a nop instruction must be inserted as indicated in Figure 15-4. The out instruction sets the "SYNC LATCH" signal at the positive edge of the clock. In this case, the delay tpd through the synchronizer is 1 system clock period. Figure 15-4. Synchronization when Reading a Software Assigned Pin Value
SYSTEM CLK r16 INSTRUCTIONS SYNC LATCH PINxn r17
0x00 t pd 0xFF out PORTx, r16 nop 0xFF
in r17, PINx
The following code example shows how to set port B pins 0 and 1 high, 2 and 3 low, and define the port pins from 4 to 7 as input with pull-ups assigned to port pins 6 and 7. The resulting pin values are read back again, but as previously discussed, a nop instruction is included to be able to read back the value recently assigned to some of the pins. 70
8042A-AVR-07/09
ATmega16HVB/32HVB
Assembly Code Example(1)
... ; Define pull-ups and set outputs high ; Define directions for port pins ldi ldi out out nop ; Read port pins in ... r16,PINB r16,(1<; Insert nop for synchronization
C Code Example
unsigned char i; ... /* Define pull-ups and set outputs high */ /* Define directions for port pins */ PORTB = (1<15.2.5
Digital Input Enable and Sleep Modes As shown in Figure 15-2 on page 68, the digital input signal can be clamped to ground at the input of the schmiSchmidtt-trigger. The signal denoted SLEEP in the figure, is set by the MCU Sleep Controller in Power-save mode to avoid high power consumption if some input signals are left floating, or have an analog signal level close to VREG/2. SLEEP is overridden for port pins enabled as external interrupt pins. If the external interrupt request is not enabled, SLEEP is active also for these pins. SLEEP is also overridden by various other alternate functions as described in "Alternate Port Functions" on page 72. If a logic high level ("one") is present on an asynchronous external interrupt pin configured as "Interrupt on Rising Edge, Falling Edge, or Any Logic Change on Pin" while the external interrupt is not enabled, the corresponding External Interrupt Flag will be set when resuming from the above mentioned Sleep mode, as the clamping in these sleep mode produces the requested logic change.
71
8042A-AVR-07/09
ATmega16HVB/32HVB
15.2.6 Unconnected Pins If some pins are unused, it is recommended to ensure that these pins have a defined level. Even though most of the digital inputs are disabled in the deep sleep modes as described above, floating inputs should be avoided to reduce current consumption in all other modes where the digital inputs are enabled (Reset, Active mode and Idle mode). The simplest method to ensure a defined level of an unused pin, is to enable the internal pull-up. In this case, the pull-up will be disabled during reset. If low power consumption during reset is important, it is recommended to use an external pull-up or pull-down. Connecting unused pins directly to VCC or GND is not recommended, since this may cause excessive currents if the pin is accidentally configured as an output.
15.3
Alternate Port Functions
Many low voltage port pins have alternate functions in addition to being general digital I/Os. Figure 15-5 shows how the port pin control signals from the simplified Figure 15-2 on page 68 can be overridden by alternate functions. The overriding signals may not be present in all port pins, but the figure serves as a generic description applicable to all port pins in the AVR microcontroller family. Figure 15-5. Alternate Port Functions(1)
PUOExn PUOVxn
1 0
PUD
DDOExn DDOVxn
1 0
D Q DDxn Q CLR
PVOExn PVOVxn
WDx RESET RDx
1 Pxn 0
Q D
1 0
PORTxn
DIEOExn DIEOVxn
1 0
Q CLR
PTOExn WPx
RESET RRx
WRx
SLEEP SYNCHRONIZER
D
SET
RPx
Q
D
Q
PINxn L
CLR
Q
CLR
Q
clk I/O
DIxn
AIOxn
PUOExn: PUOVxn: DDOExn: DDOVxn: PVOExn: PVOVxn: DIEOExn: DIEOVxn: SLEEP: PTOExn:
Pxn PULL-UP OVERRIDE ENABLE Pxn PULL-UP OVERRIDE VALUE Pxn DATA DIRECTION OVERRIDE ENABLE Pxn DATA DIRECTION OVERRIDE VALUE Pxn PORT VALUE OVERRIDE ENABLE Pxn PORT VALUE OVERRIDE VALUE Pxn DIGITAL INPUT-ENABLE OVERRIDE ENABLE Pxn DIGITAL INPUT-ENABLE OVERRIDE VALUE SLEEP CONTROL Pxn, PORT TOGGLE OVERRIDE ENABLE
PUD: WDx: RDx: RRx: WRx: RPx: WPx: clkI/O: DIxn: AIOxn:
PULLUP DISABLE WRITE DDRx READ DDRx READ PORTx REGISTER WRITE PORTx READ PORTx PIN WRITE PINx I/O CLOCK DIGITAL INPUT PIN n ON PORTx ANALOG INPUT/OUTPUT PIN n ON PORTx
DATA BUS
72
8042A-AVR-07/09
ATmega16HVB/32HVB
Note: 1. WRx, WPx, WDx, RRx, RPx, and RDx are common to all pins within the same port. clkI/O, SLEEP, and PUD are common to all ports. All other signals are unique for each pin.
Table 15-2 summarizes the function of the overriding signals. The pin and port indexes from Figure 15-5 on page 72 are not shown in the succeeding tables. The overriding signals are generated internally in the modules having the alternate function. Table 15-2.
Signal Name PUOE
Generic Description of Overriding Signals for Alternate Functions
Full Name Pull-up Override Enable Pull-up Override Value Data Direction Override Enable Data Direction Override Value Description If this signal is set, the pull-up enable is controlled by the PUOV signal. If this signal is cleared, the pull-up is enabled when {DDxn, PORTxn, PUD} = 0b010. If PUOE is set, the pull-up is enabled/disabled when PUOV is set/cleared, regardless of the setting of the DDxn, PORTxn, and PUD Register bits. If this signal is set, the Output Driver Enable is controlled by the DDOV signal. If this signal is cleared, the Output driver is enabled by the DDxn Register bit. If DDOE is set, the Output Driver is enabled/disabled when DDOV is set/cleared, regardless of the setting of the DDxn Register bit. If this signal is set and the Output Driver is enabled, the port value is controlled by the PVOV signal. If PVOE is cleared, and the Output Driver is enabled, the port Value is controlled by the PORTxn Register bit. If PVOE is set, the port value is set to PVOV, regardless of the setting of the PORTxn Register bit. If PTOE is set, the PORTxn Register bit is inverted. If this bit is set, the Digital Input Enable is controlled by the DIEOV signal. If this signal is cleared, the Digital Input Enable is determined by MCU state (Normal mode, sleep mode). If DIEOE is set, the Digital Input is enabled/disabled when DIEOV is set/cleared, regardless of the MCU state (Normal mode, sleep mode). This is the Digital Input to alternate functions. In the figure, the signal is connected to the output of the schmitt trigger but before the synchronizer. Unless the Digital Input is used as a clock source, the module with the alternate function will use its own synchronizer. This is the Analog Input/output to/from alternate functions. The signal is connected directly to the pad, and can be used bidirectionally.
PUOV
DDOE
DDOV
PVOE
Port Value Override Enable Port Value Override Value Port Toggle Override Enable Digital Input Enable Override Enable Digital Input Enable Override Value
PVOV PTOE
DIEOE
DIEOV
DI
Digital Input
AIO
Analog Input/Output
The following subsections shortly describe the alternate functions for each port, and relate the overriding signals to the alternate function. Refer to the alternate function description for further details.
73
8042A-AVR-07/09
ATmega16HVB/32HVB
15.3.1 Alternate Functions of Port A The Port A pins with alternate functions are shown in Table 15-3. Table 15-3. Port A Pins Alternate Functions
Alternate Function T1/PCINT3 (Timer/Counter1 Clock Input or Pin Change Interrupt 3) T0/PCINT2 (Timer/Counter0 Clock Input or Pin Change Interrupt 2) ADC1/SGND/PCINT1 (ADC Input Channel 1, Signal Ground or Pin Change Interrupt 1) ADC0/SGND/PCINT0 (ADC Input Channel 0, Signal Ground or Pin Change Interrupt 0)
Port Pin PA3 PA2 PA1 PA0
The alternate pin configuration is as follows: * ADC0/SGND/PCINT0 - Port A, Bit0 ADC0: Voltage ADC Channel0. This pin can serve as Channel 0 Input for the Voltage ADC. SGND: Voltage ADC Signal Ground. This pin can serve as Channel 1 Signal Ground for the Voltage ADC. PCINT0. Pin Change Interrupt 0. This pin can serve as external interrupt source. * ADC1/SGND/PCINT1 - Port A, Bit1 ADC1: Voltage ADC Channel 1: This pin can serve as Channel 1 for the Voltage ADC. SGND: Voltage ADC Signal Ground. This pin can serve as Channel 0 Signal Ground for the Voltage ADC. PCINT1: Pin Change Interrupt 1. This pin can serve as external interrupt source. * T0/PCINT2 - Port A, Bit2 T0: Timer/Counter0. This pin can serve as Timer/Counter0 clock source. PCINT2: Pin Change Interrupt 2. This pin can serve as external interrupt source. * T1/PCINT3 - Port A, Bit3 T1: Timer/Counter1. This pin can serve as Timer/Counter1 clock source. PCINT3: Pin Change Interrupt 3.
74
8042A-AVR-07/09
ATmega16HVB/32HVB
These pins can serve as external interrupt sourceTable 15-4 relates the alternate functions of Port A to the overriding signals shown in Figure 15-5 on page 72. Table 15-4.
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO
Overriding Signals for Alternate Functions in PA3:PA0
PA3/T1/PCINT3 0 0 0 0 0 0 PCINT3 * PCIE0 1 T1 INPUT PCINT3 INPUT PA2/T0/PCINT2 0 0 0 0 0 0 PCINT2 * PCIE0 1 T0 INPUT PCINT2 INPUT PA1/ADC1/SGND/PCINT1 0 0 VADSC * VADMUX=ADC0 1 VADSC * VADMUX=ADC0 0 DIDR1| (PCINT1 * PCIE0) DIDR1 PCINT1 INPUT ADC1 INPUT/ SGND PA0/ADC0/SGND/PCINT0 0 0 VADSC * VADMUX=ADC1 1 VADSC * VADMUX=ADC1 0 DIDR0 | (PCINT0 * PCIE0) DIDR0 PCINT0 INPUT ADC0 INPUT/ SGND
15.3.2
Alternate Functions of Port B The Port B pins with alternate functions are shown in Table 15-5. Table 15-5.
Port Pin PB7 PB6 PB5 PB4 PB3 PB2 PB1 PB0
Port B Pins Alternate Functions
Alternate Functions MISO/PCINT11 (SPI Bus Master Input/Slave Output or Pin Change Interrupt 11) MOSI/PCINT10 (SPI Bus Master Output/Slave Input or Pin Change Interrupt 10) SCK/PCINT9 (SPI Bus Serial Clock or Pin Change Interrupt 9) SS/PCINT8 (SPI Bus Slave Select input or Pin Change Interrupt 8) PCINT7 (Pin Change Interrupt 7) PCINT6 (Pin Change Interrupt 6) CKOUT/PCINT5 (Clock output or Pin Change Interrupt 5) PCINT4/ICP00 (Pin Change Interrupt 4 or Timer/Counter0 Input Capture Trigger)
The alternate pin configuration is as follows: * MISO/PCINT11 - Port B, Bit7 MISO, Master Data input: Slave Data output pin for SPI channel. When the SPI is enabled as a Master, this pin is configured as an input regardless of the setting of DDB7. When the SPI is enabled as a Slave, the data direction of this pin is controlled by DDB7. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB7 bit. When not operating in SPI mode, this pin can serve as an external interrupt source. PCINT11: Pin Change Interrupt 11. This pin can serve as external interrupt source.
75
8042A-AVR-07/09
ATmega16HVB/32HVB
* MOSI/PCINT10 - Port B, Bit6 MOSI, SPI Master Data output: Slave Data input for SPI channel. When the SPI is enabled as a Slave, this pin is configured as an input regardless of the setting of DDB6. When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB6. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB6 bit. When not operating in SPI mode, this pin can serve as an external interrupt source. PCINT10: Pin Change Interrupt 10. This pin can serve as external interrupt source. * SCK/PCINT9 - Port B, Bit5 SCK, Master Clock output: Slave Clock input pin for SPI channel. When the SPI is enabled as a Slave, this pin is configured as an input regardless of the setting of DDB5. When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB5. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB5 bit. PCINT9: Pin Change Interrupt 9. This pin can serve as external interrupt source. * SS/PCINT8 - Port B, Bit4 SS, Slave Select input: When the SPI is enabled as a Slave, this pin is configured as an input regardless of the setting of DDB4. As a Slave, the SPI is activated when this pin is driven low. When the SPI is enabled as a Master, the data direction of this pin is controlled by DDB4. When the pin is forced by the SPI to be an input, the pull-up can still be controlled by the PORTB4 bit. When not operating in SPI mode, this pin can serve as Clock Output, CPU Clock divided by 2. See "Clock Output" on page 28. PCINT8: Pin Change Interrupt 8. This pin can serve as external interrupt source. * PCINT7 - Port B, Bit3 PCINT7: Pin Change Interrupt 7. This pin can serve as external interrupt source. * PCINT6 - Port B, Bit2 PCINT6: Pin Change Interrupt 6. This pin can serve as external interrupt source. * CKOUT/PCINT5 - Port B, Bit1 CKOUT: Clock output. This pin can serve as clock output pin. PCINT5: Pin Change Interrupt 5. This pin can serve as external interrupt source. * ICP00/PCINT4 - Port B, Bit0 ICP00: Input Capture Timer/Counter0. This pin can serve as Input Capture Trigger for Timer/Counter0 PCINT4: Pin Change Interrupt 4. This pin can serve as external interrupt source.
76
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 15-6.
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO
Overriding Signals for Alternate Functions in PB7:PB4
PB7/MISO/PCINT11 SPE * MSTR PORTB7 * PUD SPE * MSTR 0 SPE * MSTR SPI SLAVE OUTPUT - PCINT11 * PCIE1 1 SPI MSTR INPUT PCINT11 INPUT - PB6/MOSI/PCINT10 SPE * MSTR PORTB6 * PUD SPE * MSTR 0 SPE * MSTR SPI MSTR OUTPUT - PCINT10 * PCIE1 1 SPI SLAVE INPUT PCINT10 INPUT - PB5/SCK/PCINT9 SPE * MSTR PORTB5 * PUD SPE * MSTR 0 SPE * MSTR SCK OUTPUT - PCINT9 * PCIE1 - SCK INPUT PCINT9 INPUT - PB4/SS/PCINT8 SPE * MSTR PORTB0 * PUD SPE * MSTR 0 0 0 - PCINT8 * PCIE1 1 SS INPUT PCINT8 INPUT -
Table 15-7.
Signal Name PUOE PUOV DDOE DDOV PVOE PVOV PTOE DIEOE DIEOV DI AIO
Overriding Signals for Alternate Functions in PB3:PB0
PB3/PCINT7 0 0 0 0 0 0 - PCINT7 * PCIE1 1 PCINT7 INPUT - PB2/PCINT6 0 0 0 0 0 0 - PCINT6 * PCIE1 1 PCINT6 INPUT - PB1/CKOE/PCINT5 CKOE 0 CKOE CKOE CKOE CKOUT - (PCINT6 * PCIE1)|CKOE (PCINT6 * PCIE1)|CKOE PCINT5 INPUT - PB0/PCINT4 0 0 0 0 0 0 - PCINT4 * PCIE1 1 IPC0 INPUT PCINT4 INPUT -
77
8042A-AVR-07/09
ATmega16HVB/32HVB
15.4
15.4.1
Register Description
MCUCR - MCU Control Register
Bit 0x35 (0x55) Read/Write Initial Value 7 - R 0 6 - R 0 5 CKOE R/W 0 4 PUD R/W 0 3 - R 0 2 - R 0 1 IVSEL R/W 0 0 IVCE R/W 0 MCUCR
* Bit 4 - PUD: Pull-up Disable When this bit is written to one, the pull-ups in the I/O ports are disabled even if the DDxn and PORTxn Registers are configured to enable the pull-ups ({DDxn, PORTxn} = 0b01). See "Configuring the Pin" on page 68 for more details about this feature. 15.4.2 PORTA - Port A Data Register
Bit 0x02 (0x22) Read/Write Initial Value 7
-
6
-
5
-
4
-
3
PORTA3
2
PORTA2
1
PORTA1
0
PORTA0
PORTA
R 0
R 0
R 0
R 0
R/W 0
R/W 0
R/W 0
R/W 0
15.4.3
DDRA - Port A Data Direction Register
Bit 0x01 (0x21) Read/Write Initial Value 7
-
6
-
5
-
4
-
3 DDA3 R/W 0
2 DDA2 R/W 0
1 DDA1 R/W 0
0 DDA0 R/W 0 DDRA
R 0
R 0
R 0
R 0
15.4.4
PINA - Port A Input Pins Address
Bit 0x00 (0x20) Read/Write Initial Value 7
-
6
-
5
-
4
-
3 PINA3 R/W N/A
2 PINA2 R/W N/A
1 PINA1 R/W N/A
0 PINA0 R/W N/A PINA
R N/A
R N/A
R N/A
R N/A
15.4.5
PORTB - Port B Data Register
Bit 0x05 (0x25) Read/Write Initial Value 7
PORTB7
6
PORTB6
5
PORTB5
4
PORTB4
3
PORTB3
2
PORTB2
1
PORTB1
0
PORTB0 PORTB
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
15.4.6
DDRB - Port B Data Direction Register
Bit 0x04 (0x24) Read/Write Initial Value 7 DDB7 R/W 0 6 DDB6 R/W 0 5 DDB5 R/W 0 4 DDB4 R/W 0 3 DDB3 R/W 0 2 DDB2 R/W 0 1 DDB1 R/W 0 0 DDB0 R/W 0 DDRB
15.4.7
PINB - Port B Input Pins Address
Bit 0x03 (0x23) Read/Write Initial Value 7 PINB7 R N/A 6 PINB6 R N/A 5 PINB5 R N/A 4 PINB4 R N/A 3 PINB3 R N/A 2 PINB2 R N/A 1 PINB1 R N/A 0 PINB0 R N/A PINB
78
8042A-AVR-07/09
ATmega16HVB/32HVB
16. Timer/Counter0 and Timer/Counter1 Prescalers
16.1 Overview
Timer/Counter1 and Timer/Counter0 share the same prescaler module, but the Timer/Counters can have different prescaler settings. The description below applies to both Timer/Counter1 and Timer/Counter0. 16.1.1 Internal Clock Source The Timer/Counter can be clocked directly by the system clock (by setting the CSn2:0 = 1). This provides the fastest operation, with a maximum Timer/Counter clock frequency equal to system clock frequency (fCLK_I/O). Alternatively, one of four taps from the prescaler can be used as a clock source. The prescaled clock has a frequency of either fCLK_I/O/8, fCLK_I/O/64, fCLK_I/O/256, or fCLK_I/O/1024. 16.1.2 Prescaler Reset The prescaler is free running, i.e., operates independently of the Clock Select logic of the Timer/Counter, and it is shared by Timer/Counter1 and Timer/Counter0. Since the prescaler is not affected by the Timer/Counter's clock select, the state of the prescaler will have implications for situations where a prescaled clock is used. One example of prescaling artifacts occurs when the timer is enabled and clocked by the prescaler (6 > CSn2:0 > 1). The number of system clock cycles from when the timer is enabled to the first count occurs can be from 1 to N+1 system clock cycles, where N equals the prescaler divisor (8, 64, 256, or 1024). It is possible to use the prescaler reset for synchronizing the Timer/Counter to program execution. However, care must be taken if the other Timer/Counter that shares the same prescaler also uses prescaling. A prescaler reset will affect the prescaler period for all Timer/Counters it is connected to. Figure 16-1. Prescaler for Timer/Counter
clk I/O
Clear
PSRSYNC
Tn
Synchronization
CSn0 CSn1 CSn2
n
clkTn
79
8042A-AVR-07/09
ATmega16HVB/32HVB
16.2 External Clock Source
An external clock source applied to the Tn pin can be used as Timer/Counter clock (clkTn). The Tn pin is sampled once every system clock cycle by the pin synchronization logic. The synchronized (sampled) signal is then passed through the edge detector. Figure 16-2 shows a functional equivalent block diagram of the Tn synchronization and edge detector logic. The registers are clocked at the positive edge of the internal system clock (clkI/O). The latch is transparent in the high period of the internal system clock. The edge detector generates one clkTn pulse for each positive (CSn2:0 = 7) or negative (CSn2:0 = 6) edge it detects. See Table 16-1 on page 81 for details. Figure 16-2. Tn Pin Sampling
Tn
D LE
Q
D
Q
D
Q
Tn_sync (To Clock Select Logic)
clk I/O
Synchronization Edge Detector
The synchronization and edge detector logic introduces a delay of 2.5 to 3.5 system clock cycles from an edge has been applied to the Tn pin to the counter is updated. Enabling and disabling of the clock input must be done when Tn has been stable for at least one system clock cycle, otherwise it is a risk that a false Timer/Counter clock pulse is generated. Each half period of the external clock applied must be longer than one system clock cycle to ensure correct sampling. The external clock must be guaranteed to have less than half the system clock frequency (fExtClk < fclk_I/O/2) given a 50/50% duty cycle. Since the edge detector uses sampling, the maximum frequency of an external clock it can detect is half the sampling frequency (Nyquist sampling theorem). However, due to variation of the system clock frequency and duty cycle caused by Oscillator source (crystal, resonator, and capacitors) tolerances, it is recommended that maximum frequency of an external clock source is less than fclk_I/O/2.5. An external clock source can not be prescaled.
Note: The synchronization logic on the input pins (Tn) is shown in Figure 16-2.
80
8042A-AVR-07/09
ATmega16HVB/32HVB
16.3
16.3.1
Register Description
TCCRnB - Timer/Counter n Control Register B
Bit (0x80)(0x81) Read/Write Initial Value 7 R 0 6 R 0 5 R 0 4 R 0 3 R 0 2 CSn2 R/W 0 1 CSn1 R/W 0 0 CSn0 R/W 0 TCCRnB
* Bits 2, 1, 0 - CSn2, CSn1, CSn0: Clock Select0, Bit 2, 1, and 0 The Clock Select n bits 2, 1, and 0 define the prescaling source of Timer n. Table 16-1.
CSn2 0 0 0 0 1 1 1 1
Clock Select Bit Description
CSn1 0 0 1 1 0 0 1 1 CSn0 0 1 0 1 0 1 0 1 Description No clock source (Timer/Counter stopped) clkI/O/(No prescaling) clkI/O/8 (From prescaler) clkI/O/64 (From prescaler) clkI/O/256 (From prescaler) clkI/O/1024 (From prescaler) External clock source on Tn pin. Clock on falling edge. External clock source on Tn pin. Clock on rising edge.
If external pin modes are used for the Timer/Counter n, transitions on the Tn pin will clock the counter even if the pin is configured as an output. This feature allows software control of the counting. 16.3.2 General Timer/Counter Control Register - GTCCR
Bit 0x23 (0x43) Read/Write Initial Value 7 TSM R/W 0 6 - R 0 5 - R 0 4 - R 0 3 - R 0 2 - R 0 1 - R 0 0 PSRSYNC R/W 0 GTCCR
* Bit 7 - TSM: Timer/Counter Synchronization Mode Writing the TSM bit to one activates the Timer/Counter Synchronization mode. In this mode, the value that is written to the PSRSYNC bit is kept, hence keeping the corresponding prescaler reset signals asserted. This ensures that the corresponding Timer/Counters are halted and can be configured to the same value without the risk of one of them advancing during configuration. When the TSM bit is written to zero the PSRSYNC bit is cleared by hardware, and the Timer/Counters start counting simultaneously. * Bit 0 - PSRSYNC: Prescaler Reset When this bit is one, Timer/Counter1 and Timer/Counter0 prescaler will be Reset. This bit is normally cleared immediately by hardware, except if the TSM bit is set. Note that Timer/Counter1 and Timer/Counter0 share the same prescaler and a reset of this prescaler will affect both timers.
81
8042A-AVR-07/09
ATmega16HVB/32HVB
17. Timer/Counter (T/C0,T/C1)
17.1 Features
* * * * *
Clear Timer on Compare Match (Auto Reload) Input Capture unit Four Independent Interrupt Sources (TOVn, OCFnA, OCFnB, ICFn) 8-bit Mode with Two Independent Output Compare Units 16-bit Mode with One Independent Output Compare Unit
17.2
Overview
Timer/Counter n is a general purpose 8-/16-bit Timer/Counter module, with two/one Output Compare units and Input Capture feature. ATmega16HVB/32HVB has two Timer/Counters, Timer/Counter0 and Timer/Counter1. The functionality for both Timer/Counters is described below. Timer/Counter0 and Timer/Counter1 have different Timer/Counter registers, as shown in "Register Summary" on page 254. The Timer/Counter general operation is described in 8-/16-bit mode. A simplified block diagram of the 8-/16-bit Timer/Counter is shown in Figure 17-1. CPU accessible I/O Registers, including I/O bits and I/O pins, are shown in bold. The device-specific I/O Register and bit locations are listed in the "Register Description" on page 94. Figure 17-1. 8-/16-bit Timer/Counter Block Diagram
TOVn (Int. Req.)
Count Clear Direction
clkTn Control Logic Clock Select Edge Detector ( From Prescaler ) Timer/Counter TCNTnH TCNTnL TOP Tn
=
Fixed TOP value OCnA (Int. Req.) OCnB (Int. Req.)
=
=
DATA BUS
ICFn (Int. Req.) OCRnB OCRnA
TCCRnA
TCCRnB
Edge Detector
Noise Canceler
ICPn1 ICPn0
17.2.1
Registers The Timer/Counter Low Byte Register (TCNTnL) and Output Compare Registers (OCRnA and OCRnB) are 8-bit registers. Interrupt request (abbreviated to Int.Req. in Figure 17-1 on page 82) signals are all visible in the Timer Interrupt Flag Register (TIFR). All interrupts are individually masked with the Timer Interrupt Mask Register (TIMSK). TIFR and TIMSK are not shown in the figure. In 16-bit mode the Timer/Counter consists one more 8-bit register, the Timer/Counter High Byte Register (TCNTnH). Furthermore, there is only one Output Compare Unit in 16-bit mode as the two Output Compare Registers, OCRnA and OCRnB, are combined to one 16-bit Output Compare Register. OCRnA contains the low byte of the word and OCRnB contains the higher byte of 82
8042A-AVR-07/09
ATmega16HVB/32HVB
the word. When accessing 16-bit registers, special procedures described in section "Accessing Registers in 16-bit Mode" on page 90 must be followed. The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source on the Tn pin. The Clock Select logic block controls which clock source and edge the Timer/Counter uses to increment its value. The Timer/Counter is inactive when no clock source is selected. The output from the Clock Select logic is referred to as the timer clock (clkTn). 17.2.2 Definitions Many register and bit references in this section are written in general form. A lower case "n" replaces the module number, e.g. Timer/Counter number. A lower case "x" replaces the unit, e.g. OCRnx and ICPnx describes OCRnA/B and ICP1/0x . However, when using the register or bit defines in a program, the precise form must be used, i.e., TCNT0L for accessing Timer/Counter0 counter value and so on. The definitions in Table 17-1 are also used extensively throughout the document. Table 17-1.
BOTTOM MAX
Definitions
The counter reaches the BOTTOM when it becomes 0. The counter reaches its MAXimum when it becomes 0xFF (decimal 255) in 8-bit mode or 0xFFFF (decimal 65535) in 16-bit mode. The counter reaches the TOP when it becomes equal to the highest value in the count sequence. The TOP value can be assigned to be the fixed value 0xFF/0xFFFF (MAX) or the value stored in the OCRnA Register.
TOP
17.3
Timer/Counter Clock Sources
The Timer/Counter can be clocked internally, via the prescaler, or by an external clock source. The Clock Select logic is controlled by the Clock Select (CSn2:0) bits located in the Timer/Counter Control Register n B (TCCRnB), and controls which clock source and edge the Timer/Counter uses to increment its value. The Timer/Counter is inactive when no clock source is selected. The output from the Clock Select logic is referred to as the timer clock (clkTn). For details on clock sources and prescaler, see "Timer/Counter0 and Timer/Counter1 Prescalers" on page 79
17.4
Counter Unit
The main part of the 8-bit Timer/Counter is the programmable bi-directional counter unit. Figure 17-2 on page 83 shows a block diagram of the counter and its surroundings. Figure 17-2. Counter Unit Block Diagram
DATA BUS
TOVn (Int.Req.) Clock Select Edge Detector Tn
TCNTn
count
Control Logic
clkTn
( From Prescaler ) top
83
8042A-AVR-07/09
ATmega16HVB/32HVB
Signal description (internal signals): count clkTn top Increment or decrement TCNTn by 1. Timer/Counter clock, referred to as clkTn in the following. Signalize that TCNTn has reached maximum value.
The counter is incremented at each timer clock (clkTn) until it passes its TOP value and then restarts from BOTTOM. The counting sequence is determined by the setting of the WGMn0 bits located in the Timer/Counter Control Register (TCCRnA). For more details about counting sequences, see "Timer/Counter Timing Diagrams" on page 89. clkTn can be generated from an external or internal clock source, selected by the Clock Select bits (CSn2:0). When no clock source is selected (CSn2:0 = 0) the timer is stopped. However, the TCNTn value can be accessed by the CPU, regardless of whether clkTn is present or not. A CPU write overrides (has priority over) all counter clear or count operations. The Timer/Counter Overflow Flag (TOVn) is set when the counter reaches the maximum value and it can be used for generating a CPU interrupt.
17.5
Modes of Operation
The mode of operation is defined by the Timer/Counter Width (TCWn), Input Capture Enable (ICENn) and the Waveform Generation Mode (WGMn0)bits in "TCCRnA - Timer/Counter n Control Register A" on page 94. Table 17-2 on page 84 shows the different Modes of Operation.
Table 17-2.
Mode 0 1 2 3 4 5
Modes of Operation
TCWn 0 0 1 1 0 1 WGMn0 0 1 0 1 0 0 Timer/Counter Mode of Operation Normal 8-bit Mode 8-bit CTC 16-bit Mode 16-bit CTC 8-bit Input Capture mode 16-bit Input Capture mode TOP 0xFF OCRnA 0xFFFF OCRnB, OCRnA 0xFF 0xFFFF Update of OCRx at Immediate Immediate Immediate Immediate - - TOV Flag Set on MAX (0xFF) MAX (0xFF) MAX (0xFFFF) MAX (0xFFFF) MAX (0xFF) MAX (0xFFFF)
ICENn 0 0 0 0 1 1
17.5.1
Normal 8-bit Mode In the normal mode, the counter (TCNTnL) is incrementing until it overruns when it passes its maximum 8-bit value (MAX = 0xFF) and then restarts from the bottom (0x00), see Table 17-2 on page 84 for bit settings. The Overflow Flag (TOVn) will be set in the same timer clock cycle as the TCNTnL becomes zero. The TOVn Flag in this case behaves like a ninth bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt that automatically clears the TOVn Flag, the timer resolution can be increased by software. There are no special cases to consider in the Normal 8-bit mode, a new counter value can be written anytime. The Output Compare Unit can be used to generate interrupts at some given time.
17.5.2
Clear Timer on Compare Match (CTC) 8-bit Mode In Clear Timer on Compare or CTC mode, the OCRnA Register is used to manipulate the counter resolution, see Table 17-2 on page 84 for bit settings. In CTC mode the counter is cleared to 84
8042A-AVR-07/09
ATmega16HVB/32HVB
zero when the counter value (TCNTn) matches the OCRnA. The OCRnA defines the top value for the counter, hence also its resolution. This mode allows greater control of the Compare Match output frequency. It also simplifies the operation of counting external events. The timing diagram for the CTC mode is shown in Figure 17-3 on page 85. The counter value (TCNTn) increases until a Compare Match occurs between TCNTn and OCRnA, and then counter (TCNTn) is cleared. Figure 17-3. CTC Mode, Timing Diagram
OCnx Interrupt Flag Set
TCNTn Period
1 2 3 4
An interrupt can be generated each time the counter value reaches the TOP value by using the OCFnA Flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. However, changing TOP to a value close to BOTTOM when the counter is running with none or a low prescaler value must be done with care since the CTC mode does not have the double buffering feature. If the new value written to OCRnA is lower than the current value of TCNTn, the counter will miss the Compare Match. The counter will then have to count to its maximum value (0xFF) and wrap around starting at 0x00 before the Compare Match can occur. As for the Normal mode of operation, the TOVn Flag is set in the same timer clock cycle that the counter counts from MAX to 0x00. 17.5.3 16-bit Mode In 16-bit mode, the counter (TCNTnH/L) is a incrementing until it overruns when it passes its maximum 16-bit value (MAX = 0xFFFF) and then restarts from the bottom (0x0000), see Table 17-2 on page 84 for bit settings. The Overflow Flag (TOVn) will be set in the same timer clock cycle as the TCNTnH/L becomes zero. The TOVn Flag in this case behaves like a 17th bit, except that it is only set, not cleared. However, combined with the timer overflow interrupt that automatically clears the TOVn Flag, the timer resolution can be increased by software. There are no special cases to consider in the Normal mode, a new counter value can be written anytime. The Output Compare Unit can be used to generate interrupts at some given time. 17.5.4 Clear Timer on Compare Match (CTC) 16-bit Mode In Clear Timer on Compare 16-bit mode, OCRAnA/B Registers are used to manipulate the counter resolution, see Table 17-2 on page 84 for bit settings. In CTC mode the counter is cleared to zero when the counter value (TCNTn) matches OCRnA/B, where OCRnB represents the eight most significant bits and OCRnA represents the eight least significant bits. OCRnA/B defines the top value of the counter, hence also its resolution. This mode allows greater control of the Compare Match output frequency. It also simplifies the operation of counting external events. An interrupt can be generated each time the counter reaches the TOP value by using the OCFnA flag. If the interrupt is enabled, the interrupt handler routine can be used for updating the TOP value. However, changing the TOP to a value close the BOTTOM when the counter is running with none or a low prescaler value must be done with care since the CTC mode does not have the double buffering feature. If the new value written to OCRnA/B is lower than the current 85
8042A-AVR-07/09
ATmega16HVB/32HVB
value of TCNTn, the counter will miss the Compare Match. The counter will then have to count to its maximum value (0xFFFF) and wrap around starting at 0x0000 before Compare Match can occur. As for the 16-bit Mode, the TOVn Flag is set in the same timer clock cycle that the counter counts from MAX to 0x0000. 17.5.5 8-bit Input Capture Mode The Timer/Counter can be used in a 8-bit Input Capture mode, see Table 17-2 on page 84 for bit settings. For full description, see "Input Capture Unit" on page 86. 17.5.6 16-bit Input Capture Mode The Timer/Counter can also be used in a 16-bit Input Capture mode, see Table 17-2 on page 84 for bit settings. For full description, see "Input Capture Unit" on page 86.
17.6
Input Capture Unit
The Timer/Counter incorporates an Input Capture unit that can capture external events and give them a time-stamp indicating time of occurrence. The external signal indicates an event, or multiple events. For Timer/Counter0, the events can be applied via the PB0 pin (ICP00), or alternatively via the osi_posedge pin on the Oscillator Sampling Interface (ICP01). For Timer/Counter1, the events can be applied by the Battery Protection Interrupt (ICP10) or alternatively by the Voltage Regulator Interrupt (ICP11). The time-stamps can then be used to calculate frequency, duty-cycle, and other features of the signal applied. Alternatively the timestamps can be used for creating a log of the events. The Input Capture unit is illustrated by the block diagram shown in Figure 17-4 on page 86. The elements of the block diagram that are not directly a part of the Input Capture unit are gray shaded. Figure 17-4. Input Capture Unit Block Diagram
DATA BUS
(8-bit)
TEMP (8-bit)
OCRnB (8-bit) WRITE
OCRnA (8-bit)
TCNTnH (8-bit)
TCNTnL (8-bit)
ICRn (16-bit Register)
TCNTn (16-bit Counter)
ICSn
ICNCn
ICESn
ICPn1 ICPn0
Noise Canceler
Edge Detector
ICFn (Int.Req.)
The Output Compare Register OCRnA is a dual-purpose register that is also used as an 8-bit Input Capture Register ICRn. In 16-bit Input Capture mode the Output Compare Register OCRnB serves as the high byte of the Input Capture Register ICRn. In 8-bit Input Capture mode the Output Compare Register OCRnB is free to be used as a normal Output Compare Register,
86
8042A-AVR-07/09
ATmega16HVB/32HVB
but in 16-bit Input Capture mode the Output Compare Unit cannot be used as there are no free Output Compare Register(s). Even though the Input Capture register is called ICRn in this section, it is referring to the Output Compare Register(s). For more information on how to access the 16-bit registers refer to "Accessing Registers in 16-bit Mode" on page 90. When a change of the logic level (an event) occurs on the Input Capture pin (ICPx), and this change confirms to the setting of the edge detector, a capture will be triggered. When a capture is triggered, the value of the counter (TCNTn) is written to the Input Capture Register (ICRn). The Input Capture Flag (ICFn) is set at the same system clock as the TCNTn value is copied into Input Capture Register. If enabled (TICIEn=1), the Input Capture Flag generates an Input Capture interrupt. The ICFn flag is automatically cleared when the interrupt is executed. Alternatively the ICFn flag can be cleared by software by writing a logical one to its I/O bit location. 17.6.1 Input Capture Trigger Source The default trigger source for the Input Capture unit is the I/O port PB0 in Timer/Counter0 and the Battery Protection Interrupt in Timer/Counter1. Alternatively can the osi_posedge pin on the Oscillator Sampling Interface in Timer/Counter0 and Voltage Regulator Interrupt in Timer/Counter1 be used as trigger sources. The osi_posedge pin in Timer/Counter0 Control Register A (TCCR0A) and the Voltage Regulator Interrupt bit in the Timer/Counter1 Control Register A (TCCR1A) is selected as trigger sources by setting the Input Capture Select (ICS0/1) bit. Be aware that changing trigger source can trigger a capture. The Input Capture Flag must therefore be cleared after the change. Both Input Capture inputs are sampled using the same technique. The edge detector is also identical. However, when the noise canceler is enabled, additional logic is inserted before the edge detector, which increases the delay by four system clock cycles. An Input Capture on Timer/Counter0 can also be triggered by software by controlling the port of the PB0 pin. 17.6.2 Noise Canceler The noise canceler improves noise immunity by using a simple digital filtering scheme. The noise canceler input is monitored over four samples, and all four must be equal for changing the output that in turn is used by the edge detector. The noise canceler is enabled by setting the Input Capture Noise Canceler (ICNCn) bit in Timer/Counter Control Register n B (TCCRnB). When enabled the noise canceler introduces additional four system clock cycles of delay from a change applied to the input, to the update of the ICRn Register. The noise canceler uses the system clock and is therefore not affected by the prescaler. 17.6.3 Using the Input Capture Unit The main challenge when using the Input Capture unit is to assign enough processor capacity for handling the incoming events. The time between two events is critical. If the processor has not read the captured value in the ICRn Register before the next event occurs, the ICRn will be overwritten with a new value. In this case the result of the capture will be incorrect. When using the Input Capture interrupt, the ICRn Register should be read as early in the interrupt handler routine as possible. The maximum interrupt response time is dependent on the maximum number of clock cycles it takes to handle any of the other interrupt requests. Measurement of an external signal duty cycle requires that the trigger edge is changed after each capture. Changing the edge sensing must be done as early as possible after the ICRn Register has been read. After a change of the edge, the Input Capture Flag (ICFn) must be
87
8042A-AVR-07/09
ATmega16HVB/32HVB
cleared by software (writing a logical one to the I/O bit location). For measuring frequency only, the trigger edge change is not required. Table 17-3.
ICS0 0 1 Note:
Timer/Counter0 Input Capture Source (ICS)
Source ICP00: Port PB0 ICP01: osi_posedge pin from OSI module(1)(2)
1. See "OSI - Oscillator Sampling Interface" on page 29 for details. 2. The noise canceler cannot be used with this source.
Table 17-4.
ICS1 0 1 Note:
Timer/Counter1 Input Capture Source (ICS)
Source ICP10: Battery Protection Interrupt(1) ICP11: Voltage Regulator Interrupt(1)
1. The noise canceller will filter out the input capture and it is therefore not recommended to use noise canceler with these sources.
17.7
Output Compare Unit
The comparator continuously compares the Timer/Counter (TCNTn) with the Output Compare Registers (OCRnA and OCRnB), and whenever the Timer/Counter equals to the Output Compare Registers, the comparator signals a match. A match will set the Output Compare Flag at the next timer clock cycle. In 8-bit mode the match can set either the Output Compare Flag OCFnA or OCFnB, but in 16-bit mode the match can set only the Output Compare Flag OCFnA as there is only one Output Compare Unit. If the corresponding interrupt is enabled, the Output Compare Flag generates an Output Compare interrupt. The Output Compare Flag is automatically cleared when the interrupt is executed. Alternatively, the flag can be cleared by software by writing a logical one to its I/O bit location. Figure 17-5 on page 88 shows a block diagram of the Output Compare unit. Figure 17-5. Output Compare Unit, Block Diagram
DATA BUS
OCRnx
TCNTn
= (8/16-bit Comparator )
OCFnx (Int.Req.)
88
8042A-AVR-07/09
ATmega16HVB/32HVB
17.7.1 Compare Match Blocking by TCNT0 Write All CPU write operations to the TCNTnH/L Register will block any Compare Match that occur in the next timer clock cycle, even when the timer is stopped. This feature allows OCRnA/B to be initialized to the same value as TCNTn without triggering an interrupt when the Timer/Counter clock is enabled. 17.7.2 Using the Output Compare Unit Since writing TCNTnH/L will block all Compare Matches for one timer clock cycle, there are risks involved when changing TCNTnH/L when using the Output Compare Unit, independently of whether the Timer/Counter is running or not. If the value written to TCNTnH/L equals the OCRnA/B value, the Compare Match will be missed.
17.8
Timer/Counter Timing Diagrams
The Timer/Counter is a synchronous design and the timer clock (clkTn) is therefore shown as a clock enable signal in the following figures. The figures include information on when Interrupt Flags are set. Figure 17-6 on page 89 contains timing data for basic Timer/Counter operation. The figure shows the count sequence close to the MAX value. Figure 17-6. Timer/Counter Timing Diagram, no Prescaling
clkI/O clkTn
(clkI/O /1)
TCNTn
MAX - 1
MAX
BOTTOM
BOTTOM + 1
TOVn
Figure 17-7 on page 89 shows the same timing data, but with the prescaler enabled. Figure 17-7. Timer/Counter Timing Diagram, with Prescaler (fclk_I/O/8)
clkI/O clkTn
(clkI/O /8)
TCNTn
MAX - 1
MAX
BOTTOM
BOTTOM + 1
TOVn
Figure 17-8 on page 90 shows the setting of OCFnA and OCFnB in Normal mode.
89
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 17-8. Timer/Counter Timing Diagram, Setting of OCFnx, with Prescaler (fclk_I/O/8)
clkI/O clkTn
(clkI/O /8)
TCNTn
OCRnx - 1
OCRnx
OCRnx + 1
OCRnx + 2
OCRnx
OCRnx Value
OCFnx
Figure 17-9 on page 90 shows the setting of OCFnA and the clearing of TCNTn in CTC mode. Figure 17-9. Timer/Counter Timing Diagram, CTC mode, with Prescaler (fclk_I/O/8)
clkPCK clkTn
(clkPCK /8)
TCNTn (CTC) OCRnx
TOP - 1
TOP
BOTTOM
BOTTOM + 1
TOP
OCFnx
17.9
Accessing Registers in 16-bit Mode
In 16-bit mode (the TCWn bit is set to one) the TCNTnH/L and OCRnA/B or TCNTnL/H and OCRnB/A are 16-bit registers that can be accessed by the AVR CPU via the 8-bit data bus. The 16-bit register must be byte accessed using two read or write operations. The 16-bit Timer/Counter has a single 8-bit register for temporary storing of the high byte of the 16-bit access. The same temporary register is shared between all 16-bit registers. Accessing the low byte triggers the 16-bit read or write operation. When the low byte of a 16-bit register is written by the CPU, the high byte stored in the temporary register, and the low byte written are both copied into the 16-bit register in the same clock cycle. When the low byte of a 16-bit register is read by the CPU, the high byte of the 16-bit register is copied into the temporary register in the same clock cycle as the low byte is read. There is one exception in the temporary register usage. In the Output Compare mode the 16-bit Output Compare Register OCRnA/B is read without the temporary register, because the Output Compare Register contains a fixed value that is only changed by CPU access. However, in 16bit Input Capture mode the ICRn register formed by the OCRnA and OCRnB registers must be accessed with the temporary register. To do a 16-bit write, the high byte must be written before the low byte. For a 16-bit read, the low byte must be read before the high byte.
90
8042A-AVR-07/09
ATmega16HVB/32HVB
The following code examples show how to access the 16-bit timer registers assuming that no interrupts updates the temporary register. The same principle can be used directly for accessing the OCRnA/B registers.
Assembly Code Example ... ; Set TCNTn to 0x01FF ldi r17,0x01 ldi r16,0xFF out TCNTnH,r17 out TCNTnL,r16 ; Read TCNTn into r17:r16 in r16,TCNTnL in r17,TCNTnH ... C Code Example unsigned int i; ... /* Set TCNTn to 0x01FF */ TCNTn = 0x1FF; /* Read TCNTn into i */ i = TCNTn; ... Note: 1. See "About Code Examples" on page 8.
The assembly code example returns the TCNTnH/L value in the r17:r16 register pair. It is important to notice that accessing 16-bit registers are atomic operations. If an interrupt occurs between the two instructions accessing the 16-bit register, and the interrupt code updates the temporary register by accessing the same or any other of the 16-bit timer registers, then the result of the access outside the interrupt will be corrupted. Therefore, when both the main code and the interrupt code update the temporary register, the main code must disable the interrupts during the 16-bit access.
91
8042A-AVR-07/09
ATmega16HVB/32HVB
The following code examples show how to do an atomic read of the TCNTn register contents. Reading any of the OCRn register can be done by using the same principle.
Assembly Code Example TIMn_ReadTCNTn: ; Save global interrupt flag in r18,SREG ; Disable interrupts cli ; Read TCNTn into r17:r16 in r16,TCNTnL in r17,TCNTnH ; Restore global interrupt flag out SREG,r18 ret C Code Example unsigned int TIMn_ReadTCNTn( void ) { unsigned char sreg; unsigned int i; /* Save global interrupt flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Read TCNTn into i */ i = TCNTn; /* Restore global interrupt flag */ SREG = sreg; return i; } Note: 1. See "About Code Examples" on page 8.
The assembly code example returns the TCNTnH/L value in the r17:r16 register pair.
92
8042A-AVR-07/09
ATmega16HVB/32HVB
The following code examples show how to do an atomic write of the TCNTnH/L register contents. Writing any of the OCRnA/B registers can be done by using the same principle.
Assembly Code Example TIMn_WriteTCNTn: ; Save global interrupt flag in r18,SREG ; Disable interrupts cli ; Set TCNTn to r17:r16 out TCNTnH,r17 out TCNTnL,r16 ; Restore global interrupt flag out SREG,r18 ret C Code Example void TIMn_WriteTCNTn( unsigned int i ) { unsigned char sreg; unsigned int i; /* Save global interrupt flag */ sreg = SREG; /* Disable interrupts */ _CLI(); /* Set TCNTn to i */ TCNTn = i; /* Restore global interrupt flag */ SREG = sreg; } Note: See "About Code Examples" on page 8.
The assembly code example requires that the r17:r16 register pair contains the value to be written to TCNTnH/L. 17.9.1 Reusing the temporary high byte register If writing to more than one 16-bit register where the high byte is the same for all registers written, then the high byte only needs to be written once. However, note that the same rule of atomic operation described previously also applies in this case.
93
8042A-AVR-07/09
ATmega16HVB/32HVB
17.10 Register Description
17.10.1 TCCRnA - Timer/Counter n Control Register A
Bit 0x24 (0x44) Read/Write Initial Value 7
TCWn
6
ICENn
5
ICNCn
4
ICESn
3
ICSn
2
-
1
-
0
WGMn0 TCCRnA
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R 0
R 0
R/W 0
* Bit 7- TCWn: Timer/Counter Width When this bit is written to one 16-bit mode is selected. Timer/Counter n width is set to 16-bits and the Output Compare Registers OCRnA and OCRnB are combined to form one 16-bit Output Compare Register. Because the 16-bit registers TCNTnH/L and OCRnB/A are accessed by the AVR CPU via the 8-bit data bus, special procedures must be followed. These procedures are described in section "Accessing Registers in 16-bit Mode" on page 90. * Bit 6- ICENn: Input Capture Mode Enable The Input Capture Mode is enabled when this bit is written to one. * Bit 5 - ICNCn: Input Capture Noise Canceler Setting this bit activates the Input Capture Noise Canceler. When the noise canceler is activated, the input from the Input Capture Source is filtered. The filter function requires four successive equal valued samples of the Input Capture Source for changing its output. The Input Capture is therefore delayed by four System Clock cycles when the noise canceler is enabled. * Bit 4 - ICESn: Input Capture Edge Select This bit selects which edge on the Input Capture Source that is used to trigger a capture event. When the ICESn bit is written to zero, a falling (negative) edge is used as trigger, and when the ICESn bit is written to one, a rising (positive) edge will trigger the capture. When a capture is triggered according to the ICESn setting, the counter value is copied into the Input Capture Register. The event will also set the Input Capture Flag (ICFn), and this can be used to cause an Input Capture Interrupt, if this interrupt is enabled. * Bit 3 - ICSn: Input Capture Select When written logic one, this bit enables the input capture function in Timer/Counter n to be triggered by the alternative Input Capture Source. To make the comparator trigger the Timer/Counter n Input Capture interrupt, the TICIEn bit in the Timer Interrupt Mask Register (TIMSK) must be set. See Table 17-3 on page 88 and Table 17-4 on page 88. * Bits 2:0 - Res: Reserved Bits These bits are reserved bits in the ATmega16HVB/32HVB and will always read as zero. * Bit 0 - WGMn0: Waveform Generation Mode This bit controls the counting sequence of the counter, the source for maximum (TOP) counter value, see Figure 17-6 on page 89. Modes of operation supported by the Timer/Counter unit are: Normal mode (counter) and Clear Timer on Compare Match (CTC) mode (see "Timer/Counter Timing Diagrams" on page 89).
94
8042A-AVR-07/09
ATmega16HVB/32HVB
17.10.2 TCNTnL - Timer/Counter n Register Low Byte
Bit 0x26 (0x46) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 3 2 1 0 TCNTnL R/W 0 R/W 0 R/W 0
TCNTnL[7:0] R/W 0 R/W 0
The Timer/Counter Register TCNTnL gives direct access, both for read and write operations, to the Timer/Counter unit 8-bit counter. Writing to the TCNTnL Register blocks (disables) the Compare Match on the following timer clock. Modifying the counter (TCNTnL) while the counter is running, introduces a risk of missing a Compare Match between TCNTnL and the OCRnx Registers. In 16-bit mode the TCNTnL register contains the lower part of the 16-bit Timer/Counter n Register. 17.10.3 TCNTnH - Timer/Counter n Register High Byte
Bit 0x27 (0x47) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 3 2 1 0 TCNTnH R/W 0 R/W 0 R/W 0
TCNTnH[7:0] R/W 0 R/W 0
When 16-bit mode is selected (the TCWn bit is set to one) the Timer/Counter Register TCNTnH combined to the Timer/Counter Register TCNTnL gives direct access, both for read and write operations, to the Timer/Counter unit 16-bit counter. To ensure that both the high and low bytes are read and written simultaneously when the CPU accesses these registers, the access is performed using an 8-bit temporary high byte register (TEMP). This temporary register is shared by all the other 16-bit registers. See "Accessing Registers in 16-bit Mode" on page 90. 17.10.4 OCRnA - Timer/Counter n Output Compare Register A
Bit 0x28 (0x48) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 3 2 1 0 OCRnA R/W 0 R/W 0 R/W 0
OCRnA[7:0] R/W 0 R/W 0
The Output Compare Register A contains an 8-bit value that is continuously compared with the counter value (TCNTnL). A match can be used to generate an Output Compare interrupt. In 16-bit mode the OCRnA register contains the low byte of the 16-bit Output Compare Register. To ensure that both the high and the low bytes are written simultaneously when the CPU writes to these registers, the access is performed using an 8-bit temporary high byte register (TEMP). This temporary register is shared by all the other 16-bit registers. See "Accessing Registers in 16-bit Mode" on page 90. 17.10.5 OCRnB - Timer/Counter n Output Compare Register B
Bit 0x29 (0x49) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 3 2 1 0 OCRnB R/W 0 R/W 0 R/W 0
OCRnB[7:0] R/W 0 R/W 0
The Output Compare Register B contains an 8-bit value that is continuously compared with the counter value (TCNTnL in 8-bit mode and TCNTnH in 16-bit mode). A match can be used to generate an Output Compare interrupt.
95
8042A-AVR-07/09
ATmega16HVB/32HVB
In 16-bit mode the OCRnB register contains the high byte of the 16-bit Output Compare Register. To ensure that both the high and the low bytes are written simultaneously when the CPU writes to these registers, the access is performed using an 8-bit temporary high byte register (TEMP). This temporary register is shared by all the other 16-bit registers. See "Accessing Registers in 16-bit Mode" on page 90. 17.10.6 TIMSKn - Timer/Counter n Interrupt Mask Register
Bit (0x6E)(0x6F) Read/Write Initial Value 7 R 0 6 R 0 5 R 0 4 R 0 3 ICIEn R/W 0 2 OCIEnB R/W 0 1 OCIEnA R/W 0 0 TOIEn R 0 TIMSKn
* Bit 3 - ICIEn: Timer/Counter n Input Capture Interrupt Enable When this bit is written to one, and the I-flag in the Status Register is set (interrupts globally enabled), the Timer/Counter n Input Capture interrupt is enabled. The corresponding Interrupt Vector (See Section "12." on page 52.) is executed when the ICFn flag, located in TIFRn, is set. * Bit 2 - OCIEnB: Timer/Counter n Output Compare Match B Interrupt Enable When the OCIEnB bit is written to one, and the I-bit in the Status Register is set, the Timer/Counter Compare Match B interrupt is enabled. The corresponding interrupt is executed if a Compare Match in Timer/Counter occurs, i.e., when the OCFnB bit is set in the Timer/Counter Interrupt Flag Register - TIFRn. * Bit 1 - OCIEnA: Timer/Counter n Output Compare Match A Interrupt Enable When the OCIEnA bit is written to one, and the I-bit in the Status Register is set, the Timer/Counter n Compare Match A interrupt is enabled. The corresponding interrupt is executed if a Compare Match in Timer/Counter n occurs, i.e., when the OCFnA bit is set in the Timer/Counter n Interrupt Flag Register - TIFRn. * Bit 0 - TOIEn: Timer/Counter n Overflow Interrupt Enable When the TOIEn bit is written to one, and the I-bit in the Status Register is set, the Timer/Counter n Overflow interrupt is enabled. The corresponding interrupt is executed if an overflow in Timer/Counter n occurs, i.e., when the TOVn bit is set in the Timer/Counter n Interrupt Flag Register - TIFRn. 17.10.7 TIFRn - Timer/Counter n Interrupt Flag Register
Bit 0x15 (0x35) Read/Write Initial Value 7 R 0 6 R 0 5 R 0 4 R 0 3 ICFn R/W 0 2 OCFnB R/W 0 1 OCFnA R/W 0 0 TOVn R/W 0 TIFRn
* Bits 3 - ICFn: Timer/Counter n Input Capture Flag This flag is set when a capture event occurs, according to the setting of ICENn, ICESn and ICSn bits in the TCCRnA Register. ICFn is automatically cleared when the Input Capture Interrupt Vector is executed. Alternatively, ICFn can be cleared by writing a logic one to its bit location.
96
8042A-AVR-07/09
ATmega16HVB/32HVB
* Bit 2 - OCFnB: Output Compare Flag n B The OCFnB bit is set when a Compare Match occurs between the Timer/Counter and the data in OCRnB - Output Compare Register n B. OCFnB is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCFnB is cleared by writing a logic one to the flag. When the I-bit in SREG, OCIEnB (Timer/Counter Compare B Match Interrupt Enable), and OCFnB are set, the Timer/Counter Compare Match Interrupt is executed. The OCFnB is not set in 16-bit Output Compare mode when the Output Compare Register OCRnB is used as the high byte of the 16-bit Output Compare Register or in 16-bit Input Capture mode when the Output Compare Register OCRnB is used as the high byte of the Input Capture Register. * Bit 1- OCFnA: Output Compare Flag n A The OCFnA bit is set when a Compare Match occurs between the Timer/Counter n and the data in OCRnA - Output Compare Register n. OCFnA is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, OCFnA is cleared by writing a logic one to the flag. When the I-bit in SREG, OCIEnA (Timer/Counter n Compare Match Interrupt Enable), and OCFnA are set, the Timer/Counter n Compare Match Interrupt is executed. The OCFnA is also set in 16-bit mode when a Compare Match occurs between the Timer/Counter n and 16-bit data in OCRnB/A. The OCFnA is not set in Input Capture mode when the Output Compare Register OCRnA is used as an Input Capture Register. * Bit 0 - TOVn: Timer/Counter n Overflow Flag The bit TOVn is set when an overflow occurs in Timer/Counter n. TOVn is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TOVn is cleared by writing a logic one to the flag. When the SREG I-bit, TOIEn (Timer/Counter n Overflow Interrupt Enable), and TOVn are set, the Timer/Counter n Overflow interrupt is executed.
97
8042A-AVR-07/09
ATmega16HVB/32HVB
18. SPI - Serial Peripheral Interface
18.1 Features
* * * * * * * *
Full-duplex, Three-wire Synchronous Data Transfer Master or Slave Operation LSB First or MSB First Data Transfer Seven Programmable Bit Rates End of Transmission Interrupt Flag Write Collision Protection Flag Wake-up from Idle Mode Double Speed (CK/2) Master SPI Mode
18.2
Overview
The Serial Peripheral Interface (SPI) allows high-speed synchronous data transfer between the ATmega16HVB/32HVB and peripheral devices or between several AVR devices. When the SPI is not used, power consumption can be minimized by writing the PRSPI bit in PRR0 to one. See "PRR0 - Power Reduction Register 0" on page 40 for details on how to use the PRSPI bit. Figure 18-1. SPI Block Diagram(1)
DIVIDER /2/4/8/16/32/64/128
SPI2X
Note:
1. Refer to "Alternate Port Functions" on page 72 for SPI pin placement.
SPI2X
98
8042A-AVR-07/09
ATmega16HVB/32HVB
The interconnection between Master and Slave CPUs with SPI is shown in Figure 18-2. The system consists of two shift Registers, and a Master clock generator. The SPI Master initiates the communication cycle when pulling low the Slave Select SS pin of the desired Slave. Master and Slave prepare the data to be sent in their respective shift Registers, and the Master generates the required clock pulses on the SCK line to interchange data. Data is always shifted from Master to Slave on the Master Out - Slave In, MOSI, line, and from Slave to Master on the Master In - Slave Out, MISO, line. After each data packet, the Master will synchronize the Slave by pulling high the Slave Select, SS, line. When configured as a Master, the SPI interface has no automatic control of the SS line. This must be handled by user software before communication can start. When this is done, writing a byte to the SPI Data Register starts the SPI clock generator, and the hardware shifts the eight bits into the Slave. After shifting one byte, the SPI clock generator stops, setting the end of Transmission Flag (SPIF). If the SPI Interrupt Enable bit (SPIE) in the SPCR Register is set, an interrupt is requested. The Master may continue to shift the next byte by writing it into SPDR, or signal the end of packet by pulling high the Slave Select, SS line. The last incoming byte will be kept in the Buffer Register for later use. When configured as a Slave, the SPI interface will remain sleeping with MISO tri-stated as long as the SS pin is driven high. In this state, software may update the contents of the SPI Data Register, SPDR, but the data will not be shifted out by incoming clock pulses on the SCK pin until the SS pin is driven low. As one byte has been completely shifted, the end of Transmission Flag, SPIF is set. If the SPI Interrupt Enable bit, SPIE, in the SPCR Register is set, an interrupt is requested. The Slave may continue to place new data to be sent into SPDR before reading the incoming data. The last incoming byte will be kept in the Buffer Register for later use. Figure 18-2. SPI Master-slave Interconnection
SHIFT ENABLE
The system is single buffered in the transmit direction and double buffered in the receive direction. This means that bytes to be transmitted cannot be written to the SPI Data Register before the entire shift cycle is completed. When receiving data, however, a received character must be read from the SPI Data Register before the next character has been completely shifted in. Otherwise, the first byte is lost. In SPI Slave mode, the control logic will sample the incoming signal of the SCK pin. To ensure correct sampling of the clock signal, the frequency of the SPI clock should never exceed fosc/4. When the SPI is enabled, the data direction of the MOSI, MISO, SCK, and SS pins is overridden according to Table 18-1 on page 100. For more details on automatic port overrides, refer to "Alternate Port Functions" on page 72.
99
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 18-1.
Pin MOSI MISO SCK SS Note:
SPI Pin Overrides(1)
Direction, Master SPI User Defined Input User Defined User Defined Direction, Slave SPI Input User Defined Input Input
1. See "Alternate Functions of Port B" on page 75 for a detailed description of how to define the direction of the user defined SPI pins.
The following code examples show how to initialize the SPI as a Master and how to perform a simple transmission. DDR_SPI in the examples must be replaced by the actual Data Direction Register controlling the SPI pins. DD_MOSI, DD_MISO and DD_SCK must be replaced by the actual data direction bits for these pins. E.g. if MOSI is placed on pin PB5, replace DD_MOSI with DDB5 and DDR_SPI with DDRB.
100
8042A-AVR-07/09
ATmega16HVB/32HVB
Assembly Code Example(1)
SPI_MasterInit: ; Set MOSI and SCK output, all others input ldi out ldi out ret SPI_MasterTransmit: ; Start transmission of data (r16) out SPDR,r16 Wait_Transmit: ; Wait for transmission complete sbis SPSR,SPIF rjmp Wait_Transmit ret r17,(1<; Enable SPI, Master, set clock rate fck/16
C Code Example(1)
void SPI_MasterInit(void) { /* Set MOSI and SCK output, all others input */ DDR_SPI = (1<101
8042A-AVR-07/09
ATmega16HVB/32HVB
The following code examples show how to initialize the SPI as a Slave and how to perform a simple reception. Assembly Code Example(1)
SPI_SlaveInit: ; Set MISO output, all others input ldi out ldi out ret SPI_SlaveReceive: ; Wait for reception complete sbis SPSR,SPIF rjmp SPI_SlaveReceive ; Read received data and return in ret r16,SPDR r17,(1<; Enable SPI
C Code Example(1)
void SPI_SlaveInit(void) { /* Set MISO output, all others input */ DDR_SPI = (1<102
8042A-AVR-07/09
ATmega16HVB/32HVB
18.3
18.3.1
SS Pin Functionality
Slave Mode When the SPI is configured as a Slave, the Slave Select (SS) pin is always input. When SS is held low, the SPI is activated, and MISO becomes an output if configured so by the user. All other pins are inputs. When SS is driven high, all pins are inputs, and the SPI is passive, which means that it will not receive incoming data. Note that the SPI logic will be reset once the SS pin is driven high. The SS pin is useful for packet/byte synchronization to keep the slave bit counter synchronous with the master clock generator. When the SS pin is driven high, the SPI slave will immediately reset the send and receive logic, and drop any partially received data in the Shift Register.
18.3.2
Master Mode When the SPI is configured as a Master (MSTR in SPCR is set), the user can determine the direction of the SS pin. If SS is configured as an output, the pin is a general output pin which does not affect the SPI system. Typically, the pin will be driving the SS pin of the SPI Slave. If SS is configured as an input, it must be held high to ensure Master SPI operation. If the SS pin is driven low by peripheral circuitry when the SPI is configured as a Master with the SS pin defined as an input, the SPI system interprets this as another master selecting the SPI as a slave and starting to send data to it. To avoid bus contention, the SPI system takes the following actions: 1. The MSTR bit in SPCR is cleared and the SPI system becomes a Slave. As a result of the SPI becoming a Slave, the MOSI and SCK pins become inputs. 2. The SPIF Flag in SPSR is set, and if the SPI interrupt is enabled, and the I-bit in SREG is set, the interrupt routine will be executed. Thus, when interrupt-driven SPI transmission is used in Master mode, and there exists a possibility that SS is driven low, the interrupt should always check that the MSTR bit is still set. If the MSTR bit has been cleared by a slave select, it must be set by the user to re-enable SPI Master mode.
18.4
Data Modes
There are four combinations of SCK phase and polarity with respect to serial data, which are determined by control bits CPHA and CPOL. The SPI data transfer formats are shown in Figure 18-3 and Figure 18-4 on page 104. Data bits are shifted out and latched in on opposite edges of the SCK signal, ensuring sufficient time for data signals to stabilize. This is clearly seen by summarizing Table 18-3 on page 105 and Table 18-4 on page 105, as done in Table 18-2. Table 18-2.
SPI Mode 0 1 2 3
SPI Modes
Conditions CPOL=0, CPHA=0 CPOL=0, CPHA=1 CPOL=1, CPHA=0 CPOL=1, CPHA=1 Leading Edge Sample (Rising) Setup (Rising) Sample (Falling) Setup (Falling) Trailing eDge Setup (Falling) Sample (Falling) Setup (Rising) Sample (Rising)
103
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 18-3. SPI Transfer Format with CPHA = 0
SCK (CPOL = 0) mode 0 SCK (CPOL = 1) mode 2 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 MISO PIN SS
MSB first (DORD = 0) MSB LSB first (DORD = 1) LSB
Bit 6 Bit 1
Bit 5 Bit 2
Bit 4 Bit 3
Bit 3 Bit 4
Bit 2 Bit 5
Bit 1 Bit 6
LSB MSB
Figure 18-4. SPI Transfer Format with CPHA = 1
SCK (CPOL = 0) mode 1 SCK (CPOL = 1) mode 3 SAMPLE I MOSI/MISO CHANGE 0 MOSI PIN CHANGE 0 MISO PIN SS
MSB first (DORD = 0) LSB first (DORD = 1)
MSB LSB
Bit 6 Bit 1
Bit 5 Bit 2
Bit 4 Bit 3
Bit 3 Bit 4
Bit 2 Bit 5
Bit 1 Bit 6
LSB MSB
104
8042A-AVR-07/09
ATmega16HVB/32HVB
18.5
18.5.1
Register Description
SPCR - SPI Control Register
Bit 0x2C (0x4C) Read/Write Initial Value 7 SPIE R/W 0 6 SPE R/W 0 5 DORD R/W 0 4 MSTR R/W 0 3 CPOL R/W 0 2 CPHA R/W 0 1 SPR1 R/W 0 0 SPR0 R/W 0 SPCR
* Bit 7 - SPIE: SPI Interrupt Enable This bit causes the SPI interrupt to be executed if SPIF bit in the SPSR Register is set and the if the Global Interrupt Enable bit in SREG is set. * Bit 6 - SPE: SPI Enable When the SPE bit is written to one, the SPI is enabled. This bit must be set to enable any SPI operations. * Bit 5 - DORD: Data Order When the DORD bit is written to one, the LSB of the data word is transmitted first. When the DORD bit is written to zero, the MSB of the data word is transmitted first. * Bit 4 - MSTR: Master/Slave Select This bit selects Master SPI mode when written to one, and Slave SPI mode when written logic zero. If SS is configured as an input and is driven low while MSTR is set, MSTR will be cleared, and SPIF in SPSR will become set. The user will then have to set MSTR to re-enable SPI Master mode. * Bit 3 - CPOL: Clock Polarity When this bit is written to one, SCK is high when idle. When CPOL is written to zero, SCK is low when idle. Refer to Figure 18-3 and Figure 18-4 for an example. The CPOL functionality is summarized below: Table 18-3. CPOL Functionality
CPOL 0 1 Leading Edge Rising Falling Trailing Edge Falling Rising
* Bit 2 - CPHA: Clock Phase The settings of the Clock Phase bit (CPHA) determine if data is sampled on the leading (first) or trailing (last) edge of SCK. Refer to Figure 18-3 and Figure 18-4 for an example. The CPOL functionality is summarized below: Table 18-4. CPHA Functionality
CPHA 0 1 Leading Edge Sample Setup Trailing Edge Setup Sample
105
8042A-AVR-07/09
ATmega16HVB/32HVB
* Bits 1, 0 - SPR1, SPR0: SPI Clock Rate Select 1 and 0 These two bits control the SCK rate of the device configured as a Master. SPR1 and SPR0 have no effect on the Slave. The relationship between SCK and the Oscillator Clock frequency fosc is shown in the following table:
Table 18-5.
SPI2X 0 0 0 0 1 1 1 1
Relationship Between SCK and the Oscillator Frequency
SPR1 0 0 1 1 0 0 1 1 SPR0 0 1 0 1 0 1 0 1 SCK Frequency
fosc/4 fosc/16 fosc/64 fosc/128 fosc/2 fosc/8 fosc/32 fosc/64
18.5.2
SPSR - SPI Status Register
Bit 0x2D (0x4D) Read/Write Initial Value 7 SPIF R 0 6 WCOL R 0 5 - R 0 4 - R 0 3 - R 0 2 - R 0 1 - R 0 0 SPI2X R/W 0 SPSR
* Bit 7 - SPIF: SPI Interrupt Flag When a serial transfer is complete, the SPIF Flag is set. An interrupt is generated if SPIE in SPCR is set and global interrupts are enabled. If SS is an input and is driven low when the SPI is in Master mode, this will also set the SPIF Flag. SPIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, the SPIF bit is cleared by first reading the SPI Status Register with SPIF set, then accessing the SPI Data Register (SPDR). * Bit 6 - WCOL: Write Collision Flag The WCOL bit is set if the SPI Data Register (SPDR) is written during a data transfer. The WCOL bit (and the SPIF bit) are cleared by first reading the SPI Status Register with WCOL set, and then accessing the SPI Data Register. * Bit 5:1 - Res: Reserved Bits These bits are reserved bits in the ATmega16HVB/32HVB and will always read as zero. * Bit 0 - SPI2X: Double SPI Speed Bit When this bit is written logic one the SPI speed (SCK Frequency) will be doubled when the SPI is in Master mode (see Table 18-5 on page 106). This means that the minimum SCK period will be two CPU clock periods. When the SPI is configured as Slave, the SPI is only guaranteed to work at fosc/4 or lower.
106
8042A-AVR-07/09
ATmega16HVB/32HVB
The SPI interface on the ATmega16HVB/32HVB is also used for program memory and EEPROM downloading or uploading. See Table 30.6 on page 211 for serial programming and verification. 18.5.3 SPDR - SPI Data Register
Bit 0x2E (0x4E) Read/Write Initial Value 7 MSB R/W X R/W X R/W X R/W X R/W X R/W X R/W X 6 5 4 3 2 1 0 LSB R/W X Undefined SPDR
The SPI Data Register is a read/write register used for data transfer between the Register File and the SPI Shift Register. Writing to the register initiates data transmission. Reading the register causes the Shift Register Receive buffer to be read.
107
8042A-AVR-07/09
ATmega16HVB/32HVB
19. Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC
19.1 Features
* Sampled System Coulomb Counter * Low Power Sigma-Delta ADC Optimized for Coulomb Counting * Instantaneous Current Output with 3.9 ms Conversion Time
- 13 bit Resolution (including sign bit) - Interrupt on Instantaneous Current Conversion Complete Accumulate Current Output - Programmable Conversion Time: 128/256/512/1024 ms - 18-bit Resolution (including sign bit) - Interrupt on Accumulation Current Conversion Complete Regular Current Detection Mode - Programmable Sampling Interval: 256/512/1024/2048 ms Programmable Input Voltage Range 100/200mV - Allowing Measurement of 20/40A @ 5 m Offset canceling by input polarity switching
*
* * *
19.2
Overview
ATmega16/32HVB features a dedicated Sigma-Delta ADC (CC-ADC) optimized for Coulomb Counting. By sampling the charge or discharge current flowing through an external sense resistor RSENSE, the CC-ADC is used to track the flow of current going into and out of the battery cells. Figure 19-1. Coulomb Counter Block Diagram
8-BIT DATABUS
Regular Current Level
Instantaneous Current Register
Control & Status Registers
Accumulate Current Register
IRQ Current Comparator
PI Polarity Switcher NI Sigma Delta modulator Decimation Filter
IRQ Decimation Filter
IRQ
RSENSE
The CC-ADC has a programmable voltage range allowing trade-off to be made between resolution, dynamic range and external sense resistor RSENSE.
108
8042A-AVR-07/09
ATmega16HVB/32HVB
In normal conversion mode two different output values are provided, Instantaneous Current and Accumulate Current. The Instantaneous Current Output has a short conversion time at the cost of lower resolution. The Accumulate Current Output provides a highly accurate current measurement for Coulomb Counting. The CC-ADC also provides a special Regular Current detection mode. This allows ultra-low power operation in Power-save mode when small charge or discharge currents are flowing. For offset cancellation the polarity of the input signal could be switched run time. Using this feature, the internal CC-ADC offset could be removed. See application note AVR352.
19.3
Normal Operation
When enabled the CC-ADC continuously measures the voltage over the external sense resistor RSENSE. Running in normal conversion mode, two data conversion outputs are provided. * Instantaneous Conversion Result * Accumulation Conversion Result The Instantaneous Current conversion time is fixed to 3.9 ms (typical value) allowing the output value to closely follow the input. After each Instantaneous Current conversion an interrupt is generated if the interrupt is enabled. Data from conversion will be updated in the Instantaneous Current registers CADICL and CADICH simultaneously as the interrupt is given. To avoid losing conversion data, both the low and high byte must be read within a 3.9 ms timing window after the corresponding interrupt is given. When the low byte register is read, updating of the Instantaneous Current registers and interrupts will be stopped until the high byte is read. Figure 19-2 shows an Instantaneous Current conversion diagram, where DATA4 will be lost because DATA3 reading is not completed within the limited period. Figure 19-2. Instantaneous Current Conversions
Enable
~12 ms settling 3.9 ms 3.9 ms 7.8 ms
Instantaneous Interrupt Instantaneous Data Read low byte INVALID DATA DATA 1 DATA 2 DATA 3 DATA 5
Read high byte
The Accumulate Current output is a high-resolution, high accuracy output with programmable conversion time selected by the CADAS bits in CADCSRA. The converted value is an accurate measurement of the average current flow during one conversion period. The CC-ADC generates an interrupt each time a new Accumulate Current conversion has finished if the interrupt is enabled. Data from conversion will be updated in the Accumulation Current registers - CADAC0, CADAC1, CADAC2 and CADAC3 simultaneously as the interrupt is given. To avoid losing conversion data, all bytes must be read within the selected conversion period. When the lower byte registers are read, updating of the Accumulation Current registers and interrupts will be stopped until the highest byte is read. Figure 19-3 shows an Accumulation Current conversion example, where DATA4 will be lost because DATA3 reading is not completed within the limited period.
109
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 19-3. Accumulation Current Conversions
Enable
1, 2, 3, or 4s settling 125, 250, 500, or 1000 ms 125, 250, 500, or 1000 ms 250, 500, 1000, or 2000 ms
Accumulation Interrupt Accumulation Data Read byte 1 Read byte 2 Read byte 3 Read byte 4 INVALID DATA DATA 1 DATA 2 DATA 3 DATA 5
19.4
Regular Current Detection Operation
By setting the CADSE bit in CADCSRA the CC-ADC will enter a special Regular Current Detection Sampling Mode. In this mode the CC-ADC will do one Instantaneous Current Conversion on regular sampling intervals while updating of the Accumulation Current Register is automatically disabled. The sampling interval is controlled by writing to the CADSI bits in CADCSRA. Each time a conversion is completed the result is compared with Regular Charge/Discharge Threshold levels specified in the CADRCC/CADRDC registers. If interrupt is enabled and the voltage is above/below the specified limit a Regular Current Detection Interrupt will be issued. Figure 19-4 illustrates the Regular Current Detection Mode. Figure 19-4. Regular Current Detection Mode (CADSE=1)
Regular Current Detection Operation Turn-off ~250, 500, 1000, 2000ms Measure ~12ms Turn-off ~250, 500, 1000, 2000ms Measure ~12ms
Regular Current Detection Interupt
Regular Charge Current Threshold Current through RSENSE
Regular Discharge Current Threshold
19.5
Offset Canceling by Polarity Switching
The CC-ADC offers Polarity Switching for internal offset canceling. By switching the polarity of the sampled input signal at selected time intervals, the internal voltage offset of the CC-ADC will cancel at the output. This feature prevents the CC-ADC from accumulating an offset error over time.
110
8042A-AVR-07/09
ATmega16HVB/32HVB
19.6 Configuration and Usage
While the CC-ADC is converting, the CPU can enter sleep mode and wait for an interrupt. After adding the conversion data for the Coulomb Counting, the CPU can go back to sleep again. This reduces the CPU workload, and allows more time spent in low power modes, reducing power consumption. To use the CC-ADC the bandgap voltage reference must be enabled separately, see "Voltage Reference and Temperature Sensor" on page 123. The CC-ADC will not consume power when CADEN is cleared. It is therefore recommended to switch off the CC-ADC whenever the Coulomb Counter or Regular Current Detection functions are not used. The CC-ADC is automatically disabled in Power-off mode. After the CC-ADC is enabled by setting the CADEN bit, the first four conversions do not contain useful data and should be ignored. This also applies after clearing the CADSE bit, or after changing the CADPOL or CADVSE bits. The conversion times and sampling intervals are controlled by the Ultra Low Power RC Oscillator (see "Ultra Low Power RC Oscillator" on page 27), and will depend on its actual frequency. To obtain accurate coulomb counting results, the actual conversion time should be calculated. Refer to "System Clock and Clock Options" on page 25 for details.
19.7
19.7.1
Register Description
CADCSRA - CC-ADC Control and Status Register A
Bit (0xE6) Read/Write Initial Value 7
CADEN
6
CADPOL
5
CADUB
4
CADAS1
3
CADAS0
2
CADSI1
1
CADSI0
0
CADSE CADCSRA
R/W 0
R/W 0
R 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
* Bit 7 - CADEN: CC-ADC Enable When the CADEN bit is cleared (zero), the CC-ADC is disabled, and any ongoing conversions will be terminated. When the CADEN bit is set (one), the CC-ADC will continuously measure the voltage drop over the external sense resistor R SENSE. In Power-off, the CC-ADC is always disabled. Note that the bandgap voltage reference must be enabled separately, see "Voltage Reference and Temperature Sensor" on page 123. * Bit 6 - CADPOL: CC-ADC Polarity The CADPOL bit is used to change input sampling polarity in the Sigma Delta Modulator. Writing this bit to one, the polaritiy will be negative. When the bit is zero, the polarity will be positive. * Bit 5 - CADUB: CC-ADC Update Busy The CC-ADC operates in a different clock domain than the CPU. Whenever a new value is written to CADCSRA, CADCSRC, CADRCC or CADRDC, this value must be synchronized to the CC-ADC clock domain. Subsequent writes to these registers will be blocked during this synchronization. Synchronization of one of the registers will block updating of all the others. The CADUB bit will be read as one while any of these registers is being synchronized, and will be read as zero when neither register is being synchronized. 111
8042A-AVR-07/09
ATmega16HVB/32HVB
* Bits 4:3 - CADAS1:0: CC-ADC Accumulate Current Select The CADAS bits select the conversion time for the Accumulate Current output as shown in the Table 19-1. Table 19-1. CC-ADC Accumulate Current Conversion Time
CC-ADC Accumulate Current Conversion Time(1) 128 ms 256 ms 512 ms 1s Number of CC-ADC clock Cycles 4096 8192 16384 32768
CADAS1:0 00 01 10 11 Note:
1. The actual value of depends on the actual frequency of the "Ultra Low Power RC Oscillator" on page 27. See Section "32." on page 228.
* Bits 2:1 - CADSI1:0: CC-ADC Current Sampling Interval The CADSI bits determine the current sampling interval for the Regular Current detection as shown in the Table 19-2.
Table 19-2.
CC-ADC Regular Current Sampling Interval
CC-ADC Regular Current Sampling Interval(1)(2) 256 ms (+ sampling time) 512 ms (+ sampling time) 1 s (+ sampling time) 2 s (+ sampling time) Number of CC-ADC clock Cycles 8192 (+ sampling time) 16384 (+ sampling time) 32768 (+ sampling time) 65536 (+ sampling time)
CADSI1:0 00 01 10 11 Notes:
1. The actual value of depends on the actual frequency of the "Ultra Low Power RC Oscillator" on page 27. See "Electrical Characteristics" on page 228. 2. Sampling time ~ 12 ms.
* Bit 0 - CADSE: CC-ADC Sampling Enable When the CADSE bit is written to one, the ongoing CC-ADC conversion is aborted and the CCADC enters Regular Current detection mode. 19.7.2 CADCSRB - CC-ADC Control and Status Register B
Bit (0xE7) Read/Write Initial Value 7
-
6
CADACIE
5
CADRCIE
4
CADICIE
3
-
2
CADACIF
1
CADRCIF
0
CADICIF CADCSRB
R 0
R/W 0
R 0
R/W 0
R 0
R/W 0
R/W 0
R/W 0
* Bits 7, 3 - Res: Reserved These bits are reserved bits in the ATmega16HVB/32HVB and will always read as zero. * Bit 6 - CADACIE: CC-ADC Accumulate Current Interrupt Enable When the CADACIE bit is set (one), and the I-bit in the Status Register is set (one), the CC-ADC Accumulate Current Interrupt is enabled.
112
8042A-AVR-07/09
ATmega16HVB/32HVB
* Bit 5 - CADRCIE: CC-ADC Regular Current Interrupt Enable When the CADRCIE bit is set (one), and the I-bit in the Status Register is set (one), the CC-ADC Regular Current Interrupt is enabled. * Bit 4 - CADICIE: CC-ADC Instantaneous Current Interrupt Enable When the CADICIE bit is set (one), and the I-bit in the Status Register is set (one), the CC-ADC Instantaneous Current Interrupt is enabled. * Bit 2 - CADACIF: CC-ADC Accumulate Current Interrupt Flag The CADACIF bit is set (one) after the Accumulate Current conversion has completed. The CCADC Accumulate Current Interrupt is executed if the CADACIE bit and the I-bit in SREG are set (one). CADACIF is cleared by hardware when executing the corresponding Interrupt Handling Vector. Alternatively, CADACIF is cleared by writing a logic one to the flag. * Bit 1 - CADRCIF: CC-ADC Regular Current Interrupt Flag The CADRCIF bit is set (one) when the absolute value of the result of the last CC-ADC conversion is greater than, or equal to, the compare values set by the CC-ADC Regular Charge/Discharge Current Level Registers. A positive value is compared to the Regular Charge Current Level, and a negative value is compared to the Regular Discharge Current Level. The CC-ADC Regular Current Interrupt is executed if the CADRCIE bit and the I-bit in SREG are set (one). CADRCIF is cleared by hardware when executing the corresponding Interrupt Handling Vector. Alternatively, CADRCIF is cleared by writing a logic one to the flag. * Bit 0 - CADICIF: CC-ADC Instantaneous Current Interrupt Flag The CADICIF bit is set (one) when a CC-ADC Instantaneous Current conversion is completed. The CC-ADC Instantaneous Current Interrupt is executed if the CADICIE bit and the I-bit in SREG are set (one). CADICIF is cleared by hardware when executing the corresponding Interrupt Handling vector. Alternatively, CADICIF is cleared by writing a logic one to the flag. 19.7.3 CADCSRC - CC-ADC Control and Status Register C
Bit (0xE8) Read/Write Initial Value 7
-
6
-
5
-
4
-
3
-
2
-
1
-
0
CADVSE CADCSRC
R 0
R 0
R 0
R 0
R 0
R 0
R 0
R/W 0
* Bit 7:1 - Res: Reserved These bits are reserved bits and will always read as zero. * Bit 0 - CADVSE: CC-ADC Voltage Scaling Enable Setting this bit enables the internal Voltage Scaling. When enabling the internal Voltage Scaling the internal CC-ADC reference will be divided by 2, affecting the Input Voltage Range and the resulting step-size. Table 19-3 shows the Input Voltage Range and the conversion value stepsize for the CADVSE settings.
113
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 19-3.
CADVSE 0 1
Input Voltage Range and the conversion value step-size for the CADVSE settings.
Voltage Range 200 mV 100 mV Step-size CADAC 1.67 V 0.84 V Step-size CADIC 53.7 V 26.9 V
19.7.4
CADICH and CADICL - CC-ADC Instantaneous Current
Bit (0xE5) (0xE4) Bit Read/Write 7 R R Initial Value 0 0 6 R R 0 0 5 R R 0 0 15 14 13 12 11 10 9 8 CADICH CADICL 2 R R 0 0 1 R R 0 0 0 R R 0 0
CADIC[15:8] CADIC[7:0] 4 R R 0 0 3 R R 0 0
When a CC-ADC Instantaneous Current conversion is complete, the result is found in these two registers. CADIC15:0 represents the converted result in 2's complement format. Bits 12:0 are the 13-bit ADC result (including sign), while bit 15:13 are the sign extension bits. When CADICL is read, the CC-ADC Instantaneous Current register is not updated until CADCH is read. Reading the registers in the sequence CADICL, CADICH will ensure that consistent values are read. When a conversion is completed, both registers must be read before the next conversion is completed, otherwise data will be lost. 19.7.5 CADAC3, CADAC2, CADAC1 and CADAC0 - CC-ADC Accumulate Current
Bit 31 23 15 7 (0xE3) (0xE2) (0xE1) (0xE0) Read/Write R R R Initial Value 0 0 0 R R R 0 0 0 R R R 0 0 0 30 22 14 6 29 21 13 5 28 20 12 4 27 19 11 3 26 18 10 2 25 17 9 1 24 16 8 0 CADAC3 CADAC2 CADAC1 CADAC0 R R R 0 0 0 R R R 0 0 0 R R R 0 0 0
CADAC[31:24] CADAC[23:16] CADAC[15:8] CADAC[7:0] R R R 0 0 0 R R R 0 0 0
The CADAC3, CADAC2, CADAC1 and CADAC0 Registers contain the Accumulate Current measurements in 2's complement format. Bits 17:0 are the 18-bit ADC result (including sign), while bit 31:18 are the sign extension bits. When CADAC0 is read, the CC-ADC Accumulate Current register is not updated until CADAC3 is read. Reading the registers in the sequence CADAC0, CADAC1, CADAC2, CADAC3 will ensure that consistent values are read. When a conversion is completed, all four registers must be read before the next conversion is completed, otherwise data will be lost. 114
8042A-AVR-07/09
ATmega16HVB/32HVB
19.7.6 CADRCC - CC-ADC Regular Charge Current
Bit (0xE9) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 3 2 1 0
CADRCC
CADRCC[7:0]
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
The CC-ADC Regular Charge Current Register determines the threshold level for the Regular Charge Current detection. When the result of a CC-ADC Instantaneous Current conversion is positive with a value greater than, or equal to, the Regular Charge Current level, the CC-ADC Regular Current Interrupt Flag is set. The value in this register defines the eight least significant bits of the Regular Charge Current level in 2's complement format, where the most significant bits of the Regular Charge Current level are always zero. The programmable range for the Regular Charge Current level is given in the Table 19-4. Table 19-4. Programmable Range for the Regular Charge Current Level(1)
Minimum Voltage (V) RSENSE = 1 m Current (mA) RSENSE = 5 m RSENSE = 10 m Note: 0 0 0 0 Maximum 13696/6848 13696/6848 2740/1370 1370/685 Step Size 53.7/26.9 53.7/26.9 10.7/5.4 5.3/2.7
1. Values in the table are shown with the CADVSE set to both 0 and 1.
The CC-ADC Regular Charge Current Register does not affect the setting of the CC-ADC Conversion Complete Interrupt Flag. 19.7.7 CADRDC - CC-ADC Regular Discharge Current
Bit (0xEA) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4
CADRDC[7:0]
3
2
1
0
CADRDC
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
The CC-ADC Regular Discharge Current Register determines the threshold level for the Regular Discharge Current detection. When the result of a CC-ADC Instantaneous Current conversion is negative with an absolute value greater than, or equal to, the Regular Discharge Current level, the CC-ADC Regular Current Interrupt Flag is set. The value in this register defines the eight least significant bits of the Regular Discharge Current level in 2's complement format, where the most significant bits of the Regular Discharge Current level are always one. The programmable range for the Regular Discharge Current level is given in the Table 19-5.
115
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 19-5.
Programmable Range for the Regular Discharge Current Level
Minimum Maximum 13696/6848 13696/6848 2740/1370 1370/685 Step Size 53.7/26.9 53.7/26.9 10.7/5.4 5.3/2.7
Voltage (V) RSENSE = 1 m Current (mA) RSENSE = 5 m RSENSE = 10 m Note:
0 0 0 0
1. Values in the table are shown with the CADVSE set to both 0 and 1.
The CC-ADC Regular Discharge Current Register does not affect the setting of the CC-ADC Conversion Complete Interrupt Flag.
116
8042A-AVR-07/09
ATmega16HVB/32HVB
20. Voltage ADC - 7-channel General Purpose 12-bit Sigma-Delta ADC
20.1 Features
* * * * * *
12-bit Resolution 519s Conversion Time @ 1 MHz clkVADC Four Differential Input Channels for Cell Voltage Measurements Three Single Ended Input Channels 0.2x Pre-scaling of Cell Voltages Interrupt on V-ADC Conversion Complete
20.2
Overview
The ATmega16HVB/32HVB features a 12-bit Sigma-Delta ADC. The Voltage ADC (V-ADC) is connected to seven different sources through the Input Multiplexer. There are four differential channels for Cell Voltage measurements. These channels are scaled 0.2x to comply with the Full Scale range of the V-ADC. In addition there are three single ended channels referenced to SGND. One channel is for measuring the internal temperature sensor VPTAT and two channels for measuring the voltage at ADC0 and ADC1. When the V-ADC is not used, power consumption can be minimized by writing the PRVADC bit in PRR0 to one. See "PRR0 - Power Reduction Register 0" on page 40 for details on how to use the PRVADC bit. Figure 20-1. Voltage ADC Block Schematic
V-ADC CONVERSION COMPLETE IRQ
8-BIT DATA BUS
VADCCIE VADCCIF
ADC1/SGND ADC0/SGND VTEMP
V-ADC MULTIPLEXER SEL. REG (VADMUX)
V-ADC CONTROL AND STATUS REG (VADCSR)
V-ADC CONTROL
PV4 PV3 PV2 PV1 NV INPUT MUX
12-BIT SIGMA-DELTA ADC
V-ADC DATA REGISTER (VADCL/ADCH)
Note: The shaded signals are scaled by 0.2, other signals are scaled by 1.0
VREF
SGND
20.3
Operation
To enable V-ADC conversions, the V-ADC Enable bit, VADEN, in V-ADC Control and Status Register - VADCSR must be set. If this bit is cleared, the V-ADC will be switched off, and any ongoing conversions will be terminated. The V-ADC is automatically disabled in Power-save and
117
8042A-AVR-07/09
ATmega16HVB/32HVB
Power-off mode. Note that the bandgap voltage reference must be enabled and disabled separately, see "Bandgap Calibration" on page 124. Figure 20-2. Voltage ADC Conversion Diagram
Start Conversion
Interrupt
Conversion Result OLD DATA
INVALID DATA
VA L I D
D ATA
INVALID DATA
To perform a V-ADC conversion, the analog input channel must first be selected by writing to the VADMUX register. When a logical one is written to the V-ADC Start Conversion bit VADSC, a conversion of the selected channel will start. The VADSC bit stays high as long as the conversion is in progress and will be cleared by hardware when the conversion is completed. When a conversion is in progress, the V-ADC Data Register - VADCL and VADCH will be invalid. If the System Clock Prescaler setting is changed during a V-ADC conversion, the conversion will be aborted. If a different data channel is selected while a conversion is in progress, the ADC will finish the current conversion before performing the channel change. When a conversion is finished the V-ADC Conversion Complete Interrupt Flag - VADCCIF is set. One 12-bit conversion takes 519 s to complete from the start bit is set to the interrupt flag is set. The V-ADC Data Register VADCL and VADCH will be valid until a new conversion is started. To ensure that correct data is read, both high and low byte data registers should be read before starting a new conversion. 20.3.1 Configuring PA1 and PA0 for V-ADC operation When one of the single ended channels ADC0 or ADC1 is used as analog input to the VADC, either PA0 or PA1 are used as signal ground (SGND). When ADC0/1 is selected as input channel, PA1/0 is automatically switched to SGND. The use of PA1 and PA0 as SGND is efficient for the thermistor configuration shown in "Operating Circuit" on page 225. Both thermistors, RT33 and RT34 are connected through a common divider resistor, R32, to PA0 and PA1 respectively. Both PA0 and PA1 have very high input impedance when used as ADC inputs, which makes it possible to connect two thermistors in the configuration, shown in "Operating Circuit" on page 225. However, input impedance is limited and if high accuracy is required, only one thermistor should be connected between PA0 and PA1. If two thermistors are connected, the configuration is as follows: * When measuring RT34, PA1 should be used as input channel and PA0 is automatically switched to SGND. * When measuring RT33, PA0 should be used as input channel and PA1 is automatically switched to SGND.
118
8042A-AVR-07/09
ATmega16HVB/32HVB
20.3.2 Cell inputs The V-ADC features one input channel for each battery cell to be able to measure each cell individually and to measure the total battery voltage through the input pins NV, PV1, PV2, PV3 and PV4. Note that the internal Cell Balancing uses the same pins to bypass balancing current (See "Cell Balancing" on page 154.) for details for balancing the battery cells. When balancing a cell the V-ADC should not do conversion on the selected channel, as the internal Cell balancing will affect the conversion result. The V-ADC is designed to operate on PV1 pin voltages above 2V. If the battery cell voltage on PV1 input falls below 2V the upper cell voltage appears to be lower than the its actual value. To avoid that cells get potentially overcharged software should keep the cells in balance using the internal Cell Balancing. See "Cell Balancing" on page 154. for details. When not using all the cell inputs, the unused cells should be connected to the cell below. An example external coupling in 3-cell mode is shown in Figure 20-3 on page 119. Note that even if the input is not used, it is recommended to connect the input through an external resistance to limit inverse coupling current. This is to be able to protect the battery if cells are reversed coupled during production. Figure 20-3. 1 3-cell mode connection
R PV4
R C R C R C R
PV3
PV2
ATmega16HVB/32HVB
PV1
NV
119
8042A-AVR-07/09
ATmega16HVB/32HVB
20.4
20.4.1
Register Description
VADMUX - V-ADC Multiplexer Selection Register
Bit (0x7C) Read/Write Initial Value 7
-
6
-
5
-
4
-
3
VADMUX3
2
VADMUX2
1
VADMUX1
0
VADMUX0 VADMUX
R 0
R 0
R 0
R 0
R/W 0
R/W 0
R/W 0
R/W 0
* Bit 7:4 - RES: Reserved Bits These bits are reserved bits in the ATmega16HVB/32HVB and will always read as zero. * Bit 3:0 - VADMUX3:0: V-ADC Channel Selection Bits The VADMUX bits determine the V-ADC channel selection. See Table 20-1 on page 120. Table 20-1. VADMUX channel selection
Channel Selected RESERVED CELL 1 CELL 2 CELL3 CELL4 VTEMP ADC0 ADC1 RESERVED Scale - 0.2 0.2 0.2 0.2 1.0 1.0 1.0 -
VADMUX3:0 0000 0001 0010 0011 0100 0101 0110 0111 1000...1111
20.4.2
VADCSR - V-ADC Control and Status Register
Bit (0x7A) Read/Write Initial Value 7
-
6
-
5
-
4
-
3
VADEN
2
VADSC
1
VADCCIF
0
VADCCIE VADCSR
R 0
R 0
R 0
R 0
R/W 0
R/W 0
R/W 0
R/W 0
* Bit 7:4 - RES: Reserved Bits These bits are reserved bits in the ATmega16HVB/32HVB and will always read as zero. * Bit 3 - VADEN: V-ADC Enable Writing this bit to one enables V-ADC conversion. By writing it to zero, the V-ADC is turned off. Turning the V-ADC off while a conversion is in progress will terminate this conversion. Note that the bandgap voltage reference must be enabled separately, see "Bandgap Calibration" on page 124. * Bit 2 - VADSC: Voltage ADC Start Conversion Write this bit to one to start a new conversion of the selected channel.
120
8042A-AVR-07/09
ATmega16HVB/32HVB
VADSC will read as one as long as the conversion is not finished. When the conversion is complete, it returns to zero. Writing zero to this bit has no effect. VADSC will automatically be cleared when the VADEN bit is written to zero. * Bit 1 - VADCCIF: V-ADC Conversion Complete Interrupt Flag This bit is set when a V-ADC conversion completes and the data registers are updated. The VADC Conversion Complete Interrupt is executed if the VADCCIE bit and the I-bit in SREG are set. VADCCIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, VADCCIF is cleared by writing a logical one to the flag. Beware that if doing a Read-Modify-Write on VADCSR, a pending interrupt can be lost. * Bit 0 - VADCCIE: V-ADC Conversion Complete Interrupt Enable When this bit is written to one and the I-bit in SREG is set, the V-ADC Conversion Complete Interrupt is activated. 20.4.3 VADCL and VADCH - V-ADC Data Register
Bit (0x79) (0x78) 7 Read/Write R R Initial Value 0 0 6 R R 0 0 5 R R 0 0 4 R R 0 0 15 - 14 - 13 - 12 - VADC[7:0] 3 R R 0 0 2 R R 0 0 1 R R 0 0 0 R R 0 0 11 10 VADC[11:8] 9 8 VADCH VADCL
When a V-ADC conversion is complete, the result is found in these two registers. To ensure that correct data is read, both high and low byte data registers should be read before starting a new conversion. * VADC11:0: V-ADC Conversion Result These bits represent the result from the conversion. To obtain the best absolute accuracy for the cell voltage measurements, gain and offset compensation is required. Factory calibration values are stored in the device signature row, refer to section "Reading the Signature Row from Software" on page 199 for details. The cell voltage in mV is given by:
(VADCH/L - VADC Cell n Offset) VADC Cell n Gain Calibration Word Cell n [mV] = ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------16384
The voltage on the ADCn is given by:
1- (VADCH/L - VADC ADCn Offset) VADC ADCn Gain Calibration Word ADCn[mV] = ----- ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------10 16384
When performing a Vtemp conversion, the result must be adjusted by the factory calibration value stored in the signature row, refer to section "Reading the Signature Row from Software" on page 199 for details. The absolute temperature in Kelvin is given by:
121
8042A-AVR-07/09
ATmega16HVB/32HVB
T(K) = VADCH/L VPTAT CAL -------------------------------------------------------------16384
20.4.4
DIDR0 - Digital Input Disable Register 0
Bit (0x7E) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 - R 0 2 - R 0 1 PA1DID R/W 0 0 PA0DID R/W 0 DIDR0
* Bits 7:2 - Res: Reserved Bits These bits are reserved for future use. To ensure compatibility with future devices, these bits must be written to zero when DIDR0 is written. * Bit 1:0 - PA1DID:PA0DID: Digital Input Disable When this bit is written logic one, the digital input buffer on the corresponding Port A pin is disabled. The corresponding PIN Register bit will always read as zero when this bit is set. When an analog signal is applied to the PA1:0 pin and the digital input from this pin is not needed, this bit should be written logic one to reduce power consumption in the digital input buffer.
122
8042A-AVR-07/09
ATmega16HVB/32HVB
21. Voltage Reference and Temperature Sensor
21.1 Features
* * * * * *
Accurate Voltage Reference of 1.100V Voltage Reference Calibration Interface Internal Temperature Sensor External Decoupling for Optimum Noise Performance Short Circuit Detection on the External Decoupling pin Low Power Consumption
21.2
Overview
ATmega16HVB/32HVB features a highly accurate low power On-chip Bandgap Reference Voltage, VREF of 1.100V. This reference voltage is used as reference for the On-chip Voltage Regulator, the Brown-out Detector, the internal Cell Balancing, the Battery Protection, the VADC and the CC-ADC. Figure 21-1 shows an overview of the On-chip voltage reference. Figure 21-1. Bandgap Reference Voltage
8-bit databus
BG Control and Status
BG Calibration
VPTAT
Bangap Reference w/ temperature sensor
1.1V
BG Buffer
VREF
VREFGND
IRQ
BG Short Detector
In addition to the Bandgap Reference Voltage, the Voltage Reference includes a Calibration Unit that enables run time calibration of the Reference Voltage, an On-chip temperature sensor for monitoring the die temperature, and a Bandgap Short Detector to detect short circuit conditions on the external VREF pin for highest safety.
123
8042A-AVR-07/09
ATmega16HVB/32HVB
21.3 Operation
When the device is in power-off state, the Voltage Reference will be switched off. After a Poweron reset condition the Voltage Reference will automatically be enabled. By default the Bandgap Buffer will be enabled as the buffered reference voltage is used as reference for the Battery Protection, the internal Cell Balancing, the V-ADC and the CC-ADC. If any of these modules are enabled the Bandgap Buffer must be enabled, otherwise it is recommended to disable the buffer by writing to the BGD bit in BGCSR to save power. Note that the Bandgap Buffer needs settling time before the voltage is stable. For details on settling time, see "Bandgap Buffer Settling Time" on page 125. To ensure that the battery protection has safe operation condition, the Voltage Reference includes a Short-circuit Detector. The Bandgap Short Detector continuously monitors the internal 1.100V reference voltage against the VREF pin voltage to detect potentially external short conditions to VCC or GND. If an external short condition is detected, the Bandgap Short Circuit Detection is capable of interrupting and waking up the CPU from any sleep mode. If a Bandgap Short-circuit condition occurs software should immediately disable the C-FET and D-FET. If no external protection is provided to detect such a condition it is recommended to always enable this feature, by setting the BGSCDE bit in the Bandgap Control and Status Register. The Temperature Sensor generates a voltage Proportional-To-Absolute-Temperature, VPTAT. This voltage is connected to the multiplexer at the V-ADC input and it can be used for runtime compensation of temperature drift in both the voltage reference and the On-chip Oscillator. To get the absolute temperature in degrees Kelvin, the measured VPTAT voltage must be scaled with the VPTAT factory calibration value stored in the signature row. See "Reading the Signature Row from Software" on page 199 for details. See"Electrical Characteristics" on page 228 for details on temperature accuracy.
21.4
Bandgap Calibration
To guarantee ultra low temperature drift the Voltage Reference includes two calibration registers that could be changed run-time by software. Changing values to the BGCCR IO register will change the nominal value of the Bandgap Reference Voltage, while changing values to the BGCRR IO register trims the temperature gradient of the bandgap reference. When the calibration registers are changed it will affect both the Voltage Regulator output and BOD-level. The BOD will react quickly to new detection levels, while the regulator will adjust the voltage more slowly, depending on the size of the external decoupling capacitor. To avoid that a BOD-reset is issued when calibration is done, it is recommended to change the values of the BGCC and BGCR bits stepwise, with a step size of 1, and with a hold-off time between each step. See "Electrical Characteristics" on page 228 for details on hold-off time. Changing VREF will influence the conversion results for the V-ADC and CC-ADC. It is therefore not recommended to do V-ADC and CC-ADC conversions while calibrating the bandgap. To guarantee ultra low temperature drift it is recommended to perform factory calibration using a two-step calibration algorithm. By default, Atmel factory calibration is performed at hot temperature, and the result is stored in the signature row. See "Reading the Signature Row from Software" on page 199 for details. The customer can easily implement the second calibration step in their test flow.
124
8042A-AVR-07/09
ATmega16HVB/32HVB
21.5 Bandgap Buffer Settling Time
After the Voltage Reference have been enabled it needs a settling time before the voltage is stable. The settling time depends on the size of the external decoupling capacitor. With 1uF external capacitor a minimum settling time of 2ms should be used. Until settling is done it is not recommended to enable the NFET driver (OC/OD or enter DUVR operation), Battery Protection, V-ADC or CC-ADC. Settling time is needed when the Buffer is enabled by software, or after a reset condition where the buffer is automatically enabled.
125
8042A-AVR-07/09
ATmega16HVB/32HVB
21.6
21.6.1
Register Description
BGCCR - Bandgap Calibration C Register
Bit (0xD0) Read/Write Initial Value
7 R 0
6 R 0
5 BGCC5 R/W 0
4 BGCC4 R/W 0
3 BGCC3 R/W 0
2 BGCC2 R/W 0
1 BGCC1 R/W 0
0 BGCC0 R/W 0 BGCCR
* Bits 7:6 - Res: Reserved Bits These bits are reserved bits and will always read as zero. * Bit 5:0 - BGCC5:0: BG Calibration of PTAT Current These bits are used for trimming of the nominal value of the bandgap reference voltage. These bits are binary coded. Minimum VREF: 000000, maximum VREF: 111111. Step size is approximately 2 mV. 21.6.2 BGCRR - Bandgap Calibration R Register
Bit (0xD1) Read/Write Initial Value
7 BGCR7 R/W 0
6 BGCR6 R/W 0
5 BGCR5 R/W 0
4 BGCR4 R/W 0
3 BGCR3 R/W 1
2 BGCR2 R/W 1
1 BGCR1 R/W 1
0 BGCR0 R/W 1 BGCRR
* Bit 7:0 - BGCR7:0: BG Calibration of Resistor ladder These bits are used for temperature gradient adjustment of the bandgap reference. Figure 21-2 illustrates VREF as a function of temperature. VREF has a positive temperature coefficient at low temperatures and negative temperature coefficient at high temperatures. Depending on the process variations, the top of the VREF curve may be located at higher or lower temperatures. To minimize the temperature drift in the temperature range of interest, BGCRR is used to adjust the top of the curve towards the centre of the temperature range of interest. The BGCRR bits are thermometer coded, resulting in 9 possible settings: 00000000, 00000001, 00000011, 00000111, ... , 11111111. The value 00000000 shifts the top of the VREF curve to the highest possible temperature, and the value 11111111 shifts the top of the VREF curve to the lowest possible temperature.
126
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 21-2.
21.6.3
BGCSR - Bandgap control and Status Register
Bit (0xD2) Read/Write Initial Value
7 R 0
6 R 0
5 BGD R/W 0
4 BGSCDE R/W 0
3 R 0
2 R 0
1 BGSCDIF R/W 0
0 BGSCDIE R/W 0 BGCSR
* Bits 7:6 - Res: Reserved Bits These bits are reserved bits and will always read as zero. * Bit 5 -BGD: Bandgap Disable Setting this bit to one will disable the bandgap voltage reference. This bit must be cleared (zero) before enabling Cell Balancing, CC-ADC, V-ADC or Battery Protection, and must remain unset (zero) while either of these modules are enabled. Note that after clearing this bit, a settling time is required before the voltage is stable, see "Bandgap Buffer Settling Time" on page 125. * Bit 4 - BGSCDE: Bandgap Short Circuit Detection Enabled Setting this bit to one will enable the bandgap Short Circuit Detector. This bit should be cleared if the BGD bit in the BGCSR is set to one to avoid false setting of the BGSCDIF bit. * Bits 3:2 - Res: Reserved Bits These bits are reserved bits and will always read as zero. * Bit 1 - BGSCDIF: Bandgap Short Circuit Detection Interrupt Flag The bit is set when the Bandgap Short Circuit Detector is enabled and buffered bandgap reference is different from the unbuffered Bandgap reference. The BGSCDIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, BGSCDIF is cleared by writing a logic one to its bit position.
127
8042A-AVR-07/09
ATmega16HVB/32HVB
* Bit 0 - BGSCDIE: Bandgap Short Circuit Detection Interrupt Enable When this bit is set, the Bandgap Short Circuit Detection Interrupt is enabled. The corresponding interrupt is executed if a short-circuit is detected on the External Decoupling Pin for the Voltage Reference.
128
8042A-AVR-07/09
ATmega16HVB/32HVB
22. Charger Detect
22.1 Features
* Operates directly from VFET supply * Detects when a charger is connected or disconnected by monitoring the BATT pin * Controls the operation state of the device by automatically enable/disable the internal Voltage
Regulator
* Automatically disabled when Discharge FET is ON. * Interrupt wake-up from all sleep modes
22.2
Overview
The Charger Detect module has two main functions: * Control the device operating state (Power-off or normal operation) * Detect when a charger is connected/disconnected Figure 22-1 shows a block diagram of the Charger Detect module. Figure 22-1. Charger Detect block diagram.
+ VFET
BATT
DFET_EN
POWER_OFF
BLOD
Charger Detect w/Power-on Reset
POR
SLEEP (power-off)
CHARGER_PRESENT
Charger Detect Interrupt Logic
IRQ
8-BIT DATABUS
129
8042A-AVR-07/09
ATmega16HVB/32HVB
22.3 Operation
The Charger Detect module is supplied directly from the VFET pin. When operating, the Charger Detect will monitor the voltage of the BATT pin and detect whether a charger is present or not. When the voltage on the BATT pin is above the Charger Detect Threshold level VPOT ("Electrical Characteristics" on page 228) the CHARGER_PRESENT signal will be high. This signal is edge detected to generate interrupt when a charger is connected or disconnected. The Charger Detect module will operate as long as the Discharge FET is disabled and is able to detect a charger in all sleep modes including Power-off. 22.3.1 Device operating state The Charger Detect module controls the operating state of the ATmega16HVB/32HVB by enabling/disabling the Voltage Regulator, which supplies the rest of the internal logic on the chip. If the chip is in Power-off state the Charger Detect will keep the Voltage Regulator disabled allowing only the Charger Detect module itself to operate. To be able to start from a Power-off state a charge voltage above VPOT has to be applied at the BATT pin. When a charger is connected the Charger Detect module will automatically start the Voltage Regulator. When the VREG voltage rises, a Power-on Reset (POR) is given and the chip enters normal operating mode after a reset delay corresponding to TTOUT. For details on POR, see "Power-on Reset and Charger Connect" on page 43. When the ATmega16HVB/32HVB is running in normal operation mode software or hardware could take the chip into Power-off state. For details on entering power-off by software, see "Power-off Mode" on page 38. To protect the device against software malfunctions the ATmega16HVB/32HVB has a Black-out Detector (BLOD). When a Black-out condition occurs the Charger Detect will take the chip automatically into Power-off. For details on Black-out Detection, see "Voltage Regulator" on page 132. Note that after a software power-off the BATT pin voltage has to fall below the Charger Detect threshold limit, VPOT, before the chip is able to re-enable the Voltage Regulator and start-up the device. 22.3.2 Interrupt logic When the ATmega16HVB/32HVB is running in normal operation mode, the Charger Detect is capable of giving an interrupt to the CPU if a charger is connected/disconnected or both. Interrupt is enabled/disabled by writing to the CHGDIE bit in the "CHGDCSR - Charger Detect Control and Status Register" on page 131. Interrupt is given when a charger is connected, disconnected or both depending on interrupt sense control settings. Selecting the correct interrupt sensing is done by writing to the CHGDISC bits in the "CHGDCSR - Charger Detect Control and Status Register" on page 131. Charger Detect interrupt works asynchronous and will wake the CPU from any sleep mode. The Charger Detect is automatically disabled/enabled when changing the state of the Discharge FET, and any interrupt that occurs when enabling or disabling the Discharge FET has to be carefully interpreted. * When enabling the Discharge-FET the Charger Detect module is automatically disabled. When disabling the charger detect module a charger appear to be disconnected even if a charger is present.
130
8042A-AVR-07/09
ATmega16HVB/32HVB
* When disabling the Charge-FET the Charger Detect module is automatically enabled and a charger appear to be connected.
22.4
22.4.1
Register Description
CHGDCSR - Charger Detect Control and Status Register
Bit (0xD4) Read/Write Initial Value
7 R 0
6 R 0
5 R 0
4 BATTPVL R 0
3 CHGDISC1 R/W 0
2 CHGDISC0 R/W 0
1 CHGDIF R/W 0
0 CHGDIE R/W 0 CHGDCSR
* Bit 7:5 - Res: Reserved These bits are reserved bits and will always read as zero. * Bit 4 - BATTPVL: BATT pin Voltage Level BATTPVL will read one as long when the Charger Detect module is enabled and the BATT pin voltage is above the VPOT level. Otherwise the BATTPVL will read zero. * Bit 3:2 - CHGDISC1:0: Charger Detect Interrupt Sense Control Edges in the CHARGER_PRESENT signal shown in Figure 22-1 on page 129 are used to activate a Charger Detect Interrupt if the SREG I-flag and the interrupt enable bit in CHGDCSR are set. By writing the CHGDISC bits to the values shown in Table 22-1 on page 131 the condition generating interrupt is configured. When changing the CHGDISC bits, an interrupt can occur. Therefore, it is recommended to first disable the Interrupt by clearing its CHGDIE bit in the CHGDICSR Register. Finally, the Charger Detect interrupt flag should be cleared by writing a logical one to CHGDIF bit before the interrupt is re-enabled. Table 22-1. Charger Detect Interrupt Sense Control.
Detection Charger Connect Charger Disconnect Charger Connect/Disconnect None
CHGISC1:0 00 01 10 11
* Bit 1 - CHGDIF: Charger Detect Interrupt Flag Depending on the configuration of the CHGDISC bits in the CHGDCSR, this bit is set when a charger is either connected or disconnected. The Charger Detect Interrupt is executed if the CHGDIE bit and the I-bit in SREG are set. This bit is cleared by hardware when executing the corresponding interrupt handling vector or alternatively by writing a logical one to the CHGDIF. It is recommended to write this bit to one when setting CHGDIE. * Bit 0 - CHGDIE: Charger Detect Interrupt Enable When the CHGDIE bit is set (one), and the I-bit in the Status Register is set (one), the Charger Detect Interrupt is enabled.
131
8042A-AVR-07/09
ATmega16HVB/32HVB
23. Voltage Regulator
23.1 Features
* * * *
Input voltage from 4-25V Fixed output voltage of 3.3V Battery Pack Short Detection Black-out Detection (BLOD)
23.2
Overview
ATmega16HVB/32HVB get its voltage supply through the VFET terminal. Operating range at the VFET terminal is 4 - 25V. The on-chip LDO regulator regulates the VFET terminal down to 3.3V, which is a suitable supply voltage for the internal logic, I/O lines and analog circuitry. Figure 231 illustrates the Voltage Regulator. Figure 23-1. Voltage Regulator.
Databus
ROCR
Regulator Monitor and Control Interface
DISABLE VFET
IRQ BLOD
Battery Short Detect
ENABLE
Black-out Detect
POWER-OFF
VFET
VREG
LDO Regulator
CREG
To ensure safe operating condition the Voltage Regulator has built in protection mechanisms to protect the internal circuitry if the voltage drops on either the input or output terminal. The Regulator Monitoring includes * Battery Pack Short Detector * Black-out Detector An external decoupling capacitor (CREG) of minimum 1 F is needed to ensure stable regulator operation. The same capacitor also serves as a reservoir capacitor to ensure that the chip is able to operate for some time without voltage at the VFET terminal.
132
8042A-AVR-07/09
ATmega16HVB/32HVB
23.3 Regulator Start-up
When the chip is in power-off mode the Voltage Regulator will be off and there will be no connection between VFET and VREG. The regulator is started when the Charger Detect module detects that a charger is connected (For details on Charger Detect, see "Charger Detect" on page 129). When starting the regulator the Voltage Regulator will stay in a force mode where the VREG output is raised against the VFET input voltage. As VREG increases to the target voltage level the regulator will automatically enter regulation mode, with a stable output voltage of nominally 3.3V. Figure 11-2 on page 44, in System Control and Reset illustrates the start-up sequence from power-off.
23.4
Battery Pack Short Detection
The Voltage Regulator will continuously monitor the operating condition at the VFET terminal. If the voltage at VFET drops below the Regulator Short-circuit Level (RSCL), see "Electrical Characteristics" on page 228, the Voltage Regulator enters the Battery Pack Short mode. In this mode, VFET is disconnected from VREG to avoid a quick drop in the voltage regulator output. When the voltage regulator enters this mode, the chip will be completely powered by the external reservoir capacitor (CREG). This allows the chip to operate a certain time without entering BOD reset, even if the VFET voltage is too low for the voltage regulator to operate. An interrupt is issued when the regulator enters Battery Pack Short mode, if the ROCWIE bit in ROCR Register is set. This allows actions to be taken to reduce power consumption and hence prolonging the time that CREG can be used to power the chip. In a typical short-circuit situation, VFET will drop as a consequence of high current consumption, and recover as soon as the Battery Protection module has disabled the FETs. Hence CREG should be dimensioned so that the chip can sustain operation without entering BOD reset, until the FETs are disabled either by HW or SW. To minimize power consumption when the Voltage Regulator enters the Battery Pack Short mode, the chip should enter Power-save sleep mode as soon as possible after the ROCWIF interrupt is detected. The Watchdog Timer should be configured to wake up the CPU after a time that is considered safe, see application note AVR132 for use of enhanced Watchdog Timer. Software should then check the status of the ROC flag. If the ROCS flag is cleared, normal operation may be resumed.
23.5
Black-Out Detection
To ensure that the internal logic has safe operating condition, the Voltage Regulator has built-in Black-Out Detector (BLOD). If the voltage at the VREG pin drops below the Black-out Detection Level, VBLOT, the chip will automatically enter Power-off mode.
133
8042A-AVR-07/09
ATmega16HVB/32HVB
23.6
23.6.1
Register Description
ROCR - Regulator Operating Condition Register
Bit (0xC8) Read/Write Initial Value 7 ROCS R 0 6 R 0 5 R 0 4 ROCD R/W 0 3 R 0 2 R 0 1 ROCWIF R/W 0 0 ROCWIE R/W 0 ROCR
* Bit 7 - ROCS: ROC Status This bit is set when the Voltage Regulator operates in the Battery Pack Short mode, and cleared otherwise. * Bit 6:5 - Res: Reserved Bits These bits are reserved bits and will always read as zero. * Bit 4 - ROCD: ROC Disable Setting this bit will disable the Battery Pack Short Detector and VFET will never be disconnected from the LDO Regulator. Note that it is NOT recommended to disable the Battery Pack Short Detector by setting the ROCD bit unless VFET protection is implemented externally. * Bit 3:2 - Res: reserved Bits These bits are reserved bits and will always read as zero. * Bit 1 - ROCWIF: ROC Warning Interrupt Flag The ROCWIF Flag is set when the Voltage Regulator enters the Battery Pack Short mode. The flag is cleared by writing logic one to it or by hardware, by executing the corresponding interrupt handling vector. * Bit 0 - ROCWIE: ROC Warning Interrupt Enable The ROCWIE bit enables interrupt caused by the Regulator Operating Condition Warning interrupt flag.
134
8042A-AVR-07/09
ATmega16HVB/32HVB
24. Battery Protection
24.1 Features
* * * * * * * *
Short-circuit Protection Discharge Over-current Protection Charge Over-current Protection Discharge High-current Protection Charge High-current Protection External Protection Input Programmable and Lockable Detection Levels and Reaction Times Autonomous Operation Independent of CPU
24.2
Overview
The Current Battery Protection circuitry (CBP) monitors the charge and discharge current and disables C-FET and D-FET if a Short-circuit, Over-current or High-current condition is detected. There are five different programmable detection levels: Short-circuit Detection Level, Discharge Over-current Detection Level, Charge Over-current Detection Level, Discharge High-current Detection Level, Charge High-current Detection Level. There are three different programmable delays for activating Current Battery Protection: Short-circuit Reaction Time, Over-current Reaction Time and High-current Reaction Time. After Current Battery Protection has been activated, the application software must re-enable the FETs. The Battery Protection hardware provides a hold-off time of 1 second before software can re-enable the FETs. This provides safety in case the application software should unintentionally try to re-enable the FETs too early. The activation of a protection also issues an interrupt to the CPU. The battery protection interrupts can be individually enabled and disabled by the CPU. In addition, the module offers an External Protection Input. The activation of the External Protection Input operates independently of the rest of the battery protection mechanisms. The activation/deactivation of this protection is instantaneously controlled from the External Protection Input port, and will not deactivate or affect the other battery protection mechanisms. The effect of the various battery protection types are given in Table 24-1.
Table 24-1.
Effect of Battery Protection Types
Interrupt Requests Entry Entry Entry Entry Entry Entry and/or Exit PC-FET Operational Operational Operational Operational Operational Operational C-FET Disabled Disabled Disabled Disabled Disabled Disabled D-FET Disabled Disabled Disabled Disabled Disabled Disabled Cell Balancing FETs Operational Operational Operational Operational Operational Operational MCU Operational Operational Operational Operational Operational Operational
Battery Protection Type Short-circuit Protection Discharge Over-current Protection Charge Over-current Protection Discharge High-current Protection Charge High-current Protection External Protection Input
135
8042A-AVR-07/09
ATmega16HVB/32HVB
24.3 Operation
The Current Battery Protections (CBP) monitors the cell current by sampling the shunt resistor voltage at the PPI/NNI input pins. A differential operational amplifier amplifies the voltage with a suitable gain. The output from the operational amplifier is compared to an accurate, programmable On-chip voltage reference by an Analog Comparator. If the shunt resistor voltage is above the Detection level for a time longer than the corresponding Protection Reaction Time, the chip activates Current Protection. A sampled system clocked by the internal ULP Oscillator is used for Short-circuit, Over-current, and High-current Protection. This ensures a reliable clock source, offset cancellation and low power consumption. 24.3.1 Short-circuit Protection The Short-circuit detection is provided to enable a fast response time to very large discharge currents. If the voltage at the PPI/NNI pins is above the Short-circuit Detection Level for a period longer than Short-circuit Reaction Time, the Short-circuit Protection is activated. When the Short-circuit Protection is activated, the external D-FET and C-FET are disabled and a Current Protection Timer is started. This timer ensures that the D-FET and C-FET are disabled for at least one second. The application software must then set the DFE and CFE bits in the FET Control and Status Register to re-enable normal operation. If the D-FET is re-enabled before the cause of the short-circuit condition is removed, the Short-circuit Protection will be activated again. 24.3.2 Discharge Over-current Protection If the voltage at the PPI/NNI pins is above the Discharge Over-current Detection level for a time longer than Over-current Protection Reaction Time, the chip activates Discharge Over-current Protection. When the Discharge Over-current Protection is activated, the external D-FET and C-FET are disabled and a Current Protection Timer is started. This timer ensures that the FETs are disabled for at least one second. The application software must then set the DFE and CFE bits in the FET Control and Status Register to re-enable normal operation. If the D-FET is re-enabled while the loading of the battery still is too large, the Discharge Over-current Protection will be activated again. 24.3.3 Charge Over-current Protection If the voltage at the PPI/NNI pins is above the Charge Over-current Detection level for a time longer than Over-current Protection Reaction Time, the chip activates Charge Over-current Protection. When the Charge Over-current Protection is activated, the external D-FET and C-FET are disabled and a Current Protection Timer is started. This timer ensures that the FETs are disabled for at least one second. The application software must then set the DFE and CFE bits in the FET Control and Status Register to re-enable normal operation. If the C-FET is re-enabled and the charger continues to supply too high currents, the Charge Over-current Protection will be activated again. 24.3.4 Discharge High-current Protection If the voltage at the PPI/NNI pins is above the Discharge High-current Detection level for a time longer than High-current Protection Reaction Time, the chip activates Discharge High-current Protection. 136
8042A-AVR-07/09
ATmega16HVB/32HVB
When the Discharge High-current Protection is activated, the external D-FET and C-FET are disabled and a Current Protection Timer is started. This timer ensures that the FETs are disabled for at least one second. The application software must then set the DFE and CFE bits in the FET Control and Status Register to re-enable normal operation. If the D-FET is re-enabled while the loading of the battery still is too large, the Discharge High-current Protection will be activated again. 24.3.5 Charge High-current Protection If the voltage at the PPI/NNI pins is above the Charge High-current Detection level for a time longer than High-current Protection Reaction Time, the chip activates Charge High-current Protection. When the Charge High-current Protection is activated, the external D-FET and C-FET are disabled and a Current Protection Timer is started. This timer ensures that the FETs are disabled for at least one second. The application software must then set the DFE and CFE bits in the FET Control and Status Register to re-enable normal operation. If the C-FET is re-enabled and the charger continues to supply too high currents, the Charge High-current Protection will be activated again. The Short-circuit, Over-current and High-current Protection parameters are programmable to adapt to different types of batteries. The parameters are set by writing to I/O Registers. The Parameter Registers can be locked after the initial configuration, prohibiting any further updates until the next Hardware Reset. Refer to "Register Description for Battery Protection" on page 125 for register descriptions.
24.4
External Protection Input
The External Protection Input uses the alternate port function of the General Purpose High Votlage I/O to automatically disabling the external Charge and Discharge-FET. For details, see "High Voltage I/O Ports" on page 62. Using this together with the External Interrupt (see "External Interrupt Characteristics" on page 233) features a highly flexible solution for the customer and it allows the user to customize an external protection scheme suitable for battery applications. The External Protection Input disables both the C-FET and D-FET immediately when the voltage on EXTPROT pin is pulled high (logic `1'). It is also used to disable DUVR mode if DUVR mode is enabled. Note that, unlike a Battery Protection event, the External Protection input does not affect the status of the FCSR (CFE, DFE, DUVRD, and CPS) bits. When the `high' condition disappears, the FET disabling is released immediately. DUVR mode is automatically re-entered if previously enabled. The feature is automatically enabled when the chip starts up, and can be disabled before locking the BPCR register. When locking the BPCR register, the External Protection feature is also locked. When External Protection Input is enabled, an override enable signal is set to EXTPROT pin configuring the pin as digital input. The port may be set up to give an interrupt when the pin value changes, and the protection status can be read from the port register. Note that the External Protection Input is default enabled. This means that after reset (and during reset) the port is default overridden to digital input, independent of the port register setting.
137
8042A-AVR-07/09
ATmega16HVB/32HVB
The user must disable the External Protection Input in the BPCR register before the port can be used as a normal port. Also during the reset sequence, the External Protection Input may disable the FETs. Consequently, if the External Protection feature is not used and DUVR mode is enabled in reset, the External Protection input must be held low until disabled by SW. It is recommended that the external interrupt on the External Protection Input port is configured to `any edge' to generate an interrupt to the microcontroller when using this feature, indicating that the FET protection status has changed. By reading the pin register, the External Protection status can be determined. If the pin register is set, it means that External Protection is trigged and the FET control signals in FCSR (CFE, DFE and DUVRD) are overridden and the FETs are disabled. In the opposite case, External Protection violation is not present. To ensure a safe exit from the External Protection Input condition, the FETs and DUVR mode should be disabled by SW when an External Protection condition is detected. This enables software to completely control when the FETs are switched ON again. Short pulses on the EXTPROT pin, for instance caused by temporary high voltages on the BATT pin when connecting a charger, may trigger the External Protection Input (refer to "Operating Circuit" on page 225). However if the SW does not take any action, the C-FET and D-FET will be re-enabled automatically once the External Protection condition disappears. Figure 24-1. External Protection Input example.
FC SR [CFE]
FC SR [DFE]
PC 0
INT0
OC
OD
138
8042A-AVR-07/09
ATmega16HVB/32HVB
24.5 Optimizing Usage for Low Power Consumption
In order to reduce power consumption, Short-circuit, Discharge High-current and Discharge Over-current Protection are automatically deactivated when the D-FET is disabled. The Charge Over-current and Charge High-current Protection are disabled when the C-FET is disabled. Note however that Charge Over-current Protection and Charge High-current Protection are never automatically disabled when the chip is operated in DUVR mode. Also note that none of the current protections are deactivated by the External Protection Input. To save power during an External Protection event, DFE and CFE in the FCSR register should be cleared and make sure that the chip is not operating in DUVR mode.
139
8042A-AVR-07/09
ATmega16HVB/32HVB
24.6 Battery Protection CPU Interface
The Battery Protection CPU Interface is illustrated in Figure 24-2 on page 140. Figure 24-2. Battery Protection CPU Interface
8-BIT DATA BUS
Battery Protection Parameter Lock Register
Interrupt Request LOCK? LOCK? LOCK?
10 / Interrupt Acknowledge
Battery Protection Level Register
Battery Protection Timing Register
Battery Protection Control Register
PPI NNI EXTPROT
Current Battery Protection
Battery Protection Interrupt Register
5 /
5 /
Current Protection FET Control Power-off
Each protection originating from the Current Battery Protection module has an Interrupt Flag. Each Flag can be read and cleared by the CPU, and each flag has an individual interrupt enable. All enabled flags are combined into a single battery protection interrupt request to the CPU. This interrupt can wake up the CPU from any operation mode, except Power-off. The interrupt flags are cleared by writing a logic `1' to their bit locations from the CPU. An interrupt event for the External Protection Input can be generated by enabling the external interrupt for the input port.
24.7
24.7.1
Register Description
BPPLR - Battery Protection Parameter Lock Register
Bit (0xFE) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 - R 0 2 - R 0 1 BPPLE R/W 0 0 BPPL R/W 0 BPPLR
* Bit 7:2 - Res: Reserved Bits These bits are reserved bits and will always read as zero. * Bit 1 - BPPLE: Battery Protection Parameter Lock Enable * Bit 0 - BPPL: Battery Protection Parameter Lock The BPCR, BPHCTR, BPOCTR, BPSCTR, BPDHCD, BPCHCD, BPDOCD, BPCOCD and BPSCD Battery Protection registers can be locked from any further software updates. Once
140
8042A-AVR-07/09
ATmega16HVB/32HVB
locked, these registers cannot be accessed until the next hardware reset. This provides a safe method for protecting the registers from unintentional modification by software runaway. It is recommended that software sets these registers shortly after reset, and then protect the registers from further updates. To lock these registers, the following algorithm must be followed: 1. In the same operation, write a logic one to BPPLE and BPPL. 2. Within the next four clock cycles, in the same operation, write a logic zero to BPPLE and a logic one to BPPL. 24.7.2 BPCR - Battery Protection Control Register
Bit (0xFD) Read/Write Initial Value 7 - R 0 6 - R 0 5 EPID R/W 0 4 SCD R/W 0 3 DOCD R/W 0 2 COCD R/W 0 1 DHCD R/W 0 0 CHCD R/W 0 BPCR
* Bits 7:6 - Res: Reserved Bits These bits are reserved bits and will always read as zero. * Bit 5 - EPID: External Protection Input Disable When this bit is set, the External Protection Input is disabled and any External Protection Input will be ignored. Note that this bit overrides the GPIO functionality in the External Protection Input port. If not using the External Protection Input feature, it is recommended that this bit is always set. * Bit 4 - SCD: Short Circuit Protection Disabled When the SCD bit is set, the Short-circuit Protection is disabled. The Short-circuit Detection will be disabled, and any Short-circuit condition will be ignored. * Bit 3 - DOCD: Discharge Over-current Protection Disabled When the DOCD bit is set, the Discharge Over-current Protection is disabled. The Discharge Over-current Detection will be disabled, and any Discharge Over-current condition will be ignored. * Bit 2 - COCD: Charge Over-current Protection Disable When the COCD bit is set, the Charge Over-current Protection is disabled. The Charge Overcurrent Detection will be disabled, and any Charge Over-current condition will be ignored. * Bit 1 - DHCD: Discharge High-current Protection Disabled When the DHCD bit is set, the Discharge High-current Protection is disabled. The Discharge High-current Detection will be disabled, and any Discharge High-current condition will be ignored. * Bit 0 - CHCD: Charge High-current Protection Disable When the CHCD bit is set, the Charge High-current Protection is disabled. The Charge High-current Detection will be disabled, and any Charge High-current condition will be ignored.
Note: Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator cycles + 3 CPU clock cycles is required between each time the BPCR register is written. Any writing to the BPCR register during this period will be ignored.
141
8042A-AVR-07/09
ATmega16HVB/32HVB
24.7.3 BPSCTR - Battery Protection Short-current Timing Register
Bit (0xFA) Read/Write Initial Value 7 - R 0 R/W 0 R/W 0 R/W 1 6 5 4 3 SCPT[6:0] R/W 0 R/W 0 R/W 0 R/W 0 2 1 0 BPSCTR
* Bit 7 - Res: Reserved Bits This bit is reserved in the ATmega16HVB/32HVB and will always read as zero. * Bit 6:0 - SCPT6:0: Short-current Protection Timing These bits control the delay of the Short-circuit Protection. The Short-circuit Timing can be set with a step size of 62.5 s as shown in Table 24-2 on page 142. Table 24-2. Short-circuit Protection Reaction Time. SCPT[6:0] with corresponding Short-circuit Delay Time.
Short-circuit Protection Reaction Time(1) SCPT[6:0](2) 0x00 0x01 0x02 0x03 ... 0x7E 0x7F Notes: Typ (15.5 - 70.5 s) + Td(3) (15.5 - 70.5 s) + Td(3) (78.0 - 133.0 s) + Td(3) (140.5 - 195.5 s) + Td(3) ... (7.83 - 7.88 ms) + Td(3) (7.89 - 7.95 ms) + Td(3)
1. The actual value depends on the actual frequency of the "Ultra Low Power RC Oscillator" on page 27. See "Electrical Characteristics" on page 228. 2. Initial value: SCPT[0x10](1ms). 3. An additional delay Td can be expected after enabling the Discharge FET due to initialization of the protection circuit. With nomial ULP frequency this delay is maximum 86 s. Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator cycles + 3 CPU clock cycles is required between each time the BPSCTR register is written. Any writing to the BPSCTR register during this period will be ignored.
Note:
24.7.4
BPOCTR - Battery Protection Over-current Timing Register
Bit (0xFB) Read/Write Initial Value 7 - R 0 6 - R 0 R/W 0 R/W 0 5 4 3 OCPT[5:0] R/W 0 R/W 0 R/W 1 R/W 0 2 1 0 BPOCTR
* Bit 7:6 - Res: Reserved Bits These bits are reserved in the ATmega16HVB/32HVB and will always read as zero. * Bit 5:0 - OCPT5:0: Over-current Protection Timing These bits control the delay of the Over-circuit Protection. The Over-current Timing can be set with a step size of 0.5 ms as shown in Table 24-3 on page 143.
142
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 24-3. Over-current Protection Reaction Time. OCPT[5:0] with corresponding Over-current Delay Time.
Over-current Protection Reaction Time(1) OCPT[5:0] 0x00 0x01 0x02(2) 0x03 ... 0x3E 0x3F Notes: Typ (0.0 - 0.5 ms) + Td(3) (0.0 - 0.5 ms) + Td(3) (0.5 - 1.0 ms) + Td(3) (1.0 - 1.5 ms) + Td(3) ... (30.5 - 31.0 ms) + Td(3) (31.0 - 31.5 ms) + Td(3)
1. The actual value depends on the actual frequency of the "Ultra Low Power RC Oscillator" on page 27. See "Electrical Characteristics" on page 228. 2. Initial value. 3. An additional delay Td can be expected after enabling the corresponding FET. This is related to the initialization of the protection circuitry. For the Discharge Over-Current protection, this applies when enabling the Discharge FET. For Charge Over-Current protection, this applies when enabling the Charge FET. With nominal ULP frequency this delay is maximum 0.1 ms. Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator cycles + 3 CPU clock cycles is required between each time the BPOCTR register is written. Any writing to the BPOCTR register during this period will be ignored.
Note:
24.7.5
BPHCTR - Battery Protection High-current Timing Register
Bit (0xFC) Read/Write Initial Value 7 - R 0 6 - R 0 R/W 0 R/W 0 5 4 3 HCPT[5:0] R/W 0 R/W 0 R/W 0 R/W 1 2 1 0 BPHCTR
* Bit 7:6 - Res: Reserved Bits These bits are reserved in the ATmega16HVB/32HVB and will always read as zero. * Bit 5:0 - HCPT5:0: High-current Protection Timing These bits control the delay of the High-circuit Protection. The High-current Timing can be set with a step size of 2 ms as shown in Table 24-4 on page 143. Table 24-4. High-current Protection Reaction Time. HCPT[5:0] with corresponding High-current Delay Time.
High-current Protection Reaction Time(1) HCPT[5:0] 0x00 0x01(2) 0x02 0x03 Typ (0 - 2 ms) + Td(3) (0 - 2 ms) + Td(3) (2 - 4 ms) + Td(3) (4 - 6 ms) + Td(3)
143
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 24-4. High-current Protection Reaction Time. HCPT[5:0] with corresponding High-current Delay Time.
High-current Protection Reaction Time(1) ... 0x3E 0x3F Notes: ... (122 - 124 ms) + Td(3) (124 - 126 ms) + Td(3)
1. The actual value depends on the actual frequency of the "Ultra Low Power RC Oscillator" on page 27. See "Electrical Characteristics" on page 228. 2. Initial value. 3. An additional delay Td can be expected after enabling the corresponding FET. This is related to the initialization of the protection circuitry. For the Discharge High-Current protection, this applies when enabling the Discharge FET. For Charge High-Current protection, this applies when enabling the Charge FET. With nominal ULP frequency this delay is maximum 0.2 ms. Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator cycles + 3 CPU clock cycles is required between each time the BPHCTR register is written. Any writing to the BPHCTR register during this period will be ignored.
Note:
24.7.6
BPSCD - Battery Protection Short-circuit Detection Level Register
Bit (0xF5) Read/Write Initial Value R/W 1 R/W 1 R/W 1 7 6 5 4 SCDL[7:0] R/W 1 R/W 0 R/W 0 R/W 1 R/W 1 3 2 1 0 BPSCD
* Bits 7:0 - SCDL7:0: Short-circuit Detection Level These bits sets the RSENSE voltage level for detection of Short-circuit in the Discharge Direction, as defined in Table 24-5 on page 145.
Note: Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator cycles + 3 CPU clock cycles is required between each time the BPSCD register is written. Any writing to the BPSCD register during this period will be ignored.
24.7.7
BPDOCD - Battery Protection Discharge-Over-current Detection Level Register
Bit (0xF6) Read/Write Initial Value R/W 1 R/W 1 R/W 1 7 6 5 4 3 2 1 0 BPDOCD R/W 0 R/W 1 R/W 1
DOCDL[7:0] R/W 1 R/W 0
* Bits 7:0 - DOCDL7:0: Discharge Over-current Detection Level These bits sets the RSENSE voltage level for detection of Discharge Over-current, as defined in Table 24-5 on page 145.
Note: Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator cycles + 3 CPU clock cycles is required between each time the BPDOCD register is written. Any writing to the BPDOCD register during this period will be ignored.
144
8042A-AVR-07/09
ATmega16HVB/32HVB
24.7.8 BPCOCD - Battery Protection Charge-Over-current Detection Level Register
Bit (0xF7) Read/Write Initial Value R/W 1 R/W 1 R/W 1 7 6 5 4 3 2 1 0 BPCOCD R/W 0 R/W 1 R/W 1
COCDL[7:0] R/W 1 R/W 0
* Bits 7:0 -COCDL7:0: Charge Over-current Detection Level These bits sets the RSENSE voltage level for detection of Charge Over-current, as defined in Table 24-5 on page 145.
Note: Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator cycles + 3 CPU clock cycles is required between each time the BPCOCD register is written. Any writing to the BPCOCD register during this period will be ignored.
24.7.9
BPDHCD - Battery Protection Discharge-High-current Detection Level Register
Bit (0xF8) Read/Write Initial Value R/W 1 R/W 1 R/W 1 7 6 5 4 3 2 1 0 BPDHCD R/W 0 R/W 1 R/W 1
DHCDL[7:0] R/W 1 R/W 0
* Bits 7:0 - DHCDL7:0: Discharge High-current Detection Level These bits sets the RSENSE voltage level for detection of DischargeHigh-current, as defined in Table 24-5 on page 145.
Note: Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator cycles + 3 CPU clock cycles is required between each time the BPDHCD register is written. Any writing to the BPDHCD register during this period will be ignored.
24.7.10
BPCHCD - Battery Protection Charge-High-current Detection Level Register
Bit (0xF9) Read/Write Initial Value R/W 1 R/W 1 R/W 1 7 6 5 4 3 2 1 0 BPCHCD R/W 0 R/W 1 R/W 1
CHCDL[7:0] R/W 1 R/W 0
* Bits 7:0 -CHCDL7:0: Charge High-current Detection Level These bits sets the RSENSE voltage level for detection of Charge High-current, as defined in Table 24-5 on page 145.
Note: Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator cycles + 3 CPU clock cycles is required between each time the BPCHCD register is written. Any writing to the BPCHCD register during this period will be ignored.
Table 24-5.
DL[7:0] with corresponding RSENSE voltage levels for all Current Detection Level Registers (BPSCD, BPDOCD, BPCOCD, BPDHCD, BPCHCD).
Current Protection Detection Levels
DL[7:0] 0xF3 0xF4 0xF5
Min.
Typ. (mV) 20 25 30
Max.
145
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 24-5. DL[7:0] with corresponding RSENSE voltage levels for all Current Detection Level Registers (BPSCD, BPDOCD, BPCOCD, BPDHCD, BPCHCD).
Current Protection Detection Levels 0xF6 0xF7 0xF8 0xF9 0xFA 0xFB 0xFC 0xFD 0x77 0x78 0x79 0x7A 0x7B 0x7C 0x7D 0x37 0x38 0x39 0x3A 0x3B 0x3C 0x3D 0x17 35 40 45 50 55 60 65 70 80 90 100 110 120 130 140 150 170 190 210 230 250 270 310 Reserved
All other values 24.7.11 BPIMSK - Battery Protection Interrupt Mask Register
Bit (0xF2) Read/Write Initial Value 7 R 0 6 R 0 5 R 0 4 SCIE R/W 0 3
2 COCIE R/W 0
1 DHCIE R/W 0
0 CHCIE R/W 0 BPIMSK
DOCIE R/W 0
* Bit 7:5 - Res: Reserved Bits These bits are reserved bits and will always read as zero. * Bit 4 - SCIE: Short-circuit Protection Activated Interrupt The SCIE bit enables interrupt caused by the Short-circuit Protection Activated Interrupt.
146
8042A-AVR-07/09
ATmega16HVB/32HVB
* Bit 3 - DOCIE: Discharge Over-current Protection Activated Interrupt The DOCIE bit enables interrupt caused by the Discharge Over-current Protection Activated Interrupt. * Bit 2 - COCIE: Charge Over-current Protection Activated Interrupt The COCIE bit enables interrupt caused by the Charge Over-current Protection Activated Interrupt. * Bit 1 - DHCIE : Discharger High-current Protection Activated Interrupt The DHCIE bit enables interrupt caused by the Discharge High-current Protection Activated Interrupt. * Bit 0 - CHCIE : Charger High-current Protection Activated Interrupt The CHCIE bit enables interrupt caused by the Charge High-current Protection Activated Interrupt. 24.7.12 BPIFR - Battery Protection Interrupt Flag Register
Bit (0xF3) Read/Write Initial Value 7 R 0 6 R 0 5 R 0 4 SCIF R/W 0 3 DOCIF R/W 0 2 COCIF R/W 0 1 DHCIF R/W 0 0 CHCIF R/W 0 BPIFR
* Bit 7:5 - Res: Reserved Bit These bits are reserved and will always read as zero. * Bit 4 - SCIF: Short-circuit Protection Activated Interrupt Once Short-circuit violation is detected, SCIF becomes set. The flag is cleared by writing a logic one to it. * Bit 3 - DOCIF: Discharge Over-current Protection Activated Interrupt Once Discharge Over-current violation is detected, DOCIF becomes set. The flag is cleared by writing a logic one to it. * Bit 2 - COCIF: Charge Over-current Protection Activated Interrupt Once Charge Over-current violation is detected, COCIF becomes set. The flag is cleared by writing a logic one to it. * Bit 1 - DHCIF: Discharge High-current Protection Activated Interrupt Once Discharge High-current violation is detected, DHCIF becomes set. The flag is cleared by writing a logic one to it. * Bit 0 - CHCIF: Charge High-current Protection Activated Interrupt Once Charge High-current violation is detected, CHCIF becomes set. The flag is cleared by writing a logic one to it.
147
8042A-AVR-07/09
ATmega16HVB/32HVB
25. FET Driver
25.1 Features
* High side N-channel FET driver for controlling Charge and Discharge FETs in Li-ion battery
application
* Optional Deep Under-voltage Recovery mode allowing normal operation while charging Deeply
discharged battery cells from 0-volt without an external Pre-charge FET
* Optional Pre-charge FET mode that allows chargers without pre-charge functionality to charge a
Deeply discharged battery from 0-volt
25.2
Overview
The ATmega16HVB/32HVB integrates an N-channel FET driver for turning on and off external high-side Charge and Discharge FETs in Li-ion battery packs. The FET driver is designed for outputting a high voltage gate overdrive of typically 13V during normal operation. Figure 25-1. Simplified Block diagram.
OPTIONAL QPF
RPC
RPF
QCF
QDF
+
2-4 Li-Ion Cells Battery Pack
RPVT
RCF
RDF
RBATT
PC5
OC
VFET
OD
Device / Charger
PVT
BATT
FET DRIVER
DISCHARGE_EN
DUVR_OFF
CHARGER DETECT
FET CONTROL
ATmega16HVB/32HVB
In normal operation FET is controlled by software. SW can enable and disable the Charge FET and the Discharge FET by writing to the FET Control and Status Register (FCSR).
CHARGE_EN
PWRON
148
8042A-AVR-07/09
ATmega16HVB/32HVB
For safe operation the FET driver automatically turns off both the Charge and Discharge FET if the autonomous Battery Protection circuitry (see "Battery Protection" on page 135) detects an illegal current condition. If such conditions occur, software is not allowed to turn on the FETs until the current condition has normalized. To charge deeply discharged cells the ATmega16HVB/32HVB can be configured to run in Deep Under Voltage Recovery (DUVR) mode. Using chargers with pre-charge current functionality, this allows charging of deeply discharge cells without an additional pre-charge FET. For chargers without a pre-charge limitation current, an optional pre-charge FET in parallel with a charge FET is supported to be able to charge deeply discharge cells.
25.3
25.3.1
Operation and Usage
Normal Operation In normal operation (DUVRD=1), the FET control is used to enable and disable the Charge FET and Discharge FET. Normally, the FETs are enabled and disabled by SW writing to the FET Control and Status Register (FCSR). However, the autonomous Battery Protection circuitry will if necessary override SW settings to protect the battery cells from too high Charge- or Discharge currents. Note that the CPU is never allowed to enable a FET that is disabled by the battery protection circuitry. The FET control is shown in Figure 25-1 on page 148. Figure 25-2. FET Control module.
External_Protection_Input Power-off Mode
CURRENT_PROTECTION
Current Protection Timer DUVR_OFF DUVRD
8-BIT D ATA BU S
FET Control and Status Register
CFE CHARGE_EN
DFE
DISCHARGE_EN
If Current Protection is activated by the Battery Protection circuitry both the Charge-FET and Discharge FET will be disabled by hardware. When the protection condition disappears the Current Protection Timer will ensure a hold-off time of 1 second before software can re-enable the external FETs. To turn on the Charge and Discharge FET a minimum VFET supply voltage is required. When the C-FET/D-FET is off with a total cell voltage lower than 6V, SW should not turn on the CFET/D-FET unless a charger is connected. If the total cell voltage is higher than 6V, SW could turn-on the C-FET or D-FET. Note however, if the FETs are already turned-on, the FET driver can operate in the entire supply operating range of the device.
149
8042A-AVR-07/09
ATmega16HVB/32HVB
The C-FET/D-FETs is switched on by pumping the gate OC/OD above the source voltage (PVT/BATT) of the external FET. When the gate-source voltage has reached a level higher than typically 13V the pumping frequency is reduced and is regulated to maintain the high gatesource voltage. For low VFET voltages (< 8 Volts) this level is never reached, thus the pumping frequency is not reduced. The gate-source voltage for low VFET voltages is close to 2VFET-2V. To avoid over-heating the external FET's when turning them off OC/OD is pulled quickly low. If the C-FET is disabled and D-FET enabled, discharge current will run through the body-drain diode of the C-FET and vice versa. To avoid the potential heat problem from this situation, software should ensure that the D-FET is not disabled when a large charge current is flowing, and that the C-FET is not disabled when a large discharge current is flowing. 25.3.2 DUVR - Deep Under Voltage Recovery Mode without Pre-charge FET To allow charging of deeply discharged cells using chargers with pre-charge functionality, the FET Driver can be configured to operate in Deep Under-Voltage Recovery (DUVR) mode. DUVR mode allows charging of deeply discharged cells without using an additional pre-charge FET. To enter Deep Under Voltage Recovery Mode, software should clear the DUVRD bit (DUVRD=0) in the FET Control and Status Register (FCSR). In DUVR mode the FET Driver regulates the voltage at VFET quickly to typically 4.5V by partly opening the C-FET. At this voltage the chip is fully operational. With the C-FET partly open the charger is allowed to charge the battery with a pre-charge current. As the cell voltage starts to increase above 4.5V the VFET voltage follows the cell voltage. When the total cell voltage has been charged to a voltage higher than 5V, it is safe to exit DUVR mode and to turn-on the C-FET completely. Software should then set the DUVRD bit to exit DUVR and fully open the C-FET by setting the CFET bit. Note that it is recommended that this is done in two steps. 1. Exit DUVR mode by setting the DUVRD bit. 2. Wait until register synchronization is complete (see guard time notice in "Register Description" on page 153), and enable the C-FET by setting the CFE bit. To avoid potential heating of the C-FET and D-FET in DUVR mode, the charger should not be allowed to enter quick-charge until the FET has been completely enabled and the FET driver has exit DUVR mode. It is therefore recommended to use the CC-ADC to continuously monitor the current flowing during DUVR mode charging, and to turn-off the FETs if an illegal charge current is measured. For fast tracking, it is recommended to use the CC-ADC Instantaneous Current Output. For details on CC-ADC usage, see "Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC" on page 108. Before entering DUVR-mode it is recommended to enable the D-FET. After enabling the D-FET it is recommended that SW add a hold-off time of 10ms before DUVR mode is entered. This is to make sure that the D-FET is completely enabled. To avoid that the charger enters quick-charge before the battery has exit DUVR mode, it is recommended that either 1. The battery controls when the charger is allowed to enter quick-charge. This is done by communicating to the charger over the SMBus line when the charger is allowed to enter increase the charge current. 2. The charger itself controls when to enter quick-charge by sensing the voltage at the Pack+ terminal. It is not recommended that the charger allows quick-charge until the charger senses a Pack+ voltage higher than 7V. To avoid potential heating problem SW need to ensure to exit DUVR mode and enable the C-FET before the charger sees this limit. 150
8042A-AVR-07/09
ATmega16HVB/32HVB
When the battery is started from a power-off condition by connecting a legal charger, SW should determine whether to allow charging or not before enabling the C-FET. Before allowing charging it is recommended to use the V-ADC to measure the cell temperature and cell voltages. Depending on the total cell voltage, the device should either start up in DUVR mode or in normal charging mode with the C-FET and D-FET enabled. * If the total cell voltage is below 4.5V, the battery should enter DUVR charging mode. This ensures safe operation voltage while allowing charging. * If the total cell voltage is above 4.5V, the battery should enter normal charging mode with both C-FET and D-FET enabled. The "DUVR mode charging in 3-cell mode configuration" on page 151 shows an example of charging 3 deeply discharged Li-ion cells in series using DUVR mode. Figure 25-3. DUVR mode charging in 3-cell mode configuration
14 12
Voltage
10 8 6 4 2 0
PVT VFET Pack+
RESET DUVRD CFE DFE
12
3
4
56
7
1. A charger with 12.6V charge voltage is plugged to the Pack+ pin and the ATmega16HVB/32HVB enters reset mode. Charger should be configured with a charge current limit (pre-charge current). 2. The ATmega16HVB/32HVB exit reset and initializes modules. To determine if charging should be allowed and if DUVR mode should be entered, cell temperature and cell voltages are measured by the V-ADC. 3. D-FET is enabled and the VFET voltage increase to the Pack+ level. 4. DUVR mode is entered by clearing the DUVRD bit in FCSR. The VFET voltage and the Pack+ voltage will now be regulated to approximately 4.5V. 5. The total cell voltage has reached the regulated VFET limit and VFET follows the cell voltage as the battery is charged. 6. The total cell voltage has reached 5V. DUVR mode is disabled and the C-FET can be fully enabled. DUVR mode should be disabled before the C-CFET is enabled. VFET and
151
8042A-AVR-07/09
ATmega16HVB/32HVB
Pack+ will therefore rise to the charger voltage for a short period before the C-FET is enabled. 7. Battery voltage reached charger voltage. 25.3.3 Deep Under Voltage operation with Pre-charge FET If a charger without pre-charge functionality is used, the Pre-charge FET will provide the current path and the pre-charge resistor will limit the charge current during charging of deeply over-discharged cells. After reaching sufficient battery voltage it is safe to turn on the Charge FET to increase the charge current. Deep Under Voltage Operation with Pre-charge FET is supported through PC5, which is a high voltage open drain pin. For configuration and usage of this pin, see "High Voltage I/O Ports" on page 62. 25.3.4 Operation in Reset and Power off In reset and power-off the C-FET and D-FET will be automatically turned off. Safety is remained by active pulling OC/OD hard to ground.
152
8042A-AVR-07/09
ATmega16HVB/32HVB
25.4
25.4.1
Register Description
FCSR - FET Control and Status Register
Bit (0xF0) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 DUVRD R/W 1 2 CPS R 0 1 DFE R/W 0 0 CFE R/W 0 FCSR
* Bits 7:4 - Res: Reserved Bits These bits are reserved bits in the ATmega16HVB/32HVB, and will always read as zero. * Bit 3 - DUVRD: Deep Under-voltage Recovery Disabled When the DUVRD is cleared (zero), the FET Driver will be forced to operate in Deep Under-voltage Recovery DUVR mode. See "DUVR - Deep Under Voltage Recovery Mode without Precharge FET" on page 150 for details. To avoid that the FET driver tries to switch on the C-FET during current protection or during internal reset, the DUVRD bit is overridden to one by hardware in these cases. When this bit is set (one), Deep Under-voltage Recovery mode of the FET Driver will be disabled. * Bit 2 - CPS: Current Protection Status The CPS bit shows the status of the Current Protection. This bit is set (one) when a Current Protection is active, and cleared (zero) otherwise. * Bit 1 - DFE: Discharge FET Enable When the DFE bit is cleared (zero), the Discharge FET will be disabled regardless of the state of the Battery Protection circuitry. When this bit is set (one), the Discharge FET is enabled. This bit will automatically be cleared by the CBP circuitry when Current Protection is activated. When this bit is cleared, Short-circuit, Discharge High-current and Discharge Over-current are disabled regardless of the settings in the BPCR Register. * Bit 0 - CFE: Charge FET Enable When the CFE bit is cleared (zero), the Charge FET will be disabled regardless of the state of the Battery Protection circuitry. When this bit is set (one), the Charge FET is enabled. This bit will automatically be cleared by the CBP circuitry when Current Protection is activated. When this bit is cleared and the DUVRD bit is set, Charge High-current Protection and Charge Overcurrent Protection are disabled regardless of the settings in the BPCR Register. When the DUVRD bit is cleared, the charge FET will be enabled by DUVR mode regardless of the CFE status.
Notes: 1. Due to synchronization of parameters between clock domains, a guard time of 3 ULP oscillator cycles + 3 CPU clock cycles is required between each time the FCSR register is written. Any writing to the FCSR register during this period will be ignored. 2. The NFET drivers require a minimum total cell voltage of 6V or higher or a charger connected to turn-on the FETs. Note that this limit only applies if the FET is disabled in advanced. If the FET is already enabled, the FET will be fully operational in the entire voltage range of the device (4-25V).
153
8042A-AVR-07/09
ATmega16HVB/32HVB
26. Cell Balancing
26.1 Overview
ATmega16HVB/32HVB incorporates cell balancing FETs. The chip provides one cell balancing FET for each battery cell in series. The FETs are directly controlled by the application software, allowing the cell balancing algorithms to be implemented in software. The FETs are connected in parallel with the individual battery cells. The cell balancing is illustrated in Figure 26-1. The figure shows a four-cell configuration. The cell balancing FETs are disabled in the Power-off mode. For typical current through the Cell Balancing FETs, see "Electrical Characteristics" on page 228. The Cell Balancing FETs are controlled by the CBCR. Neighbouring FETs cannot be simultaneously enabled. If trying to enable two neighbouring FETs, both will be disabled. Figure 26-1. Cell Balancing
PV4
RP
PV3
RP TCB Level Shift Cell Balancing Control Register
PV2
RP TCB Level Shift
PV1
RP TCB RP
NV
Level Shift
8-BIT DATA BUS
TCB
Level Shift
154
8042A-AVR-07/09
ATmega16HVB/32HVB
26.2
26.2.1
Register Description
CBCR - Cell Balancing Control Register
Bit (0xF1) Read/Write Initial Value 7 - R 0 6 - R 0 5 - R 0 4 - R 0 3 CBE4 R/W 0 2 CBE3 R/W 0 1 CBE2 R/W 0 0 CBE1 R/W 0 CBCR
* Bit 7:4 - Res: Reserved Bits These bits are reserved bits in the ATmega16HVB/32HVB and will always read as zero. * Bit 3 - CBE4: Cell Balancing Enable 4 When this bit is set, the integrated Cell Balancing FET between terminals PV4 and PV3 will be enabled. When the bit is cleared, the Cell Balancing FET will be disabled. The Cell Balancing FETs are always disabled in Power-off mode. CBE4 cannot be set if CBE3 is set. * Bit 2 - CBE3: Cell Balancing Enable 3 When this bit is set, the integrated Cell Balancing FET between terminals PV3 and PV2 will be enabled. When the bit is cleared, the Cell Balancing FET will be disabled. The Cell Balancing FETs are always disabled in Power-off mode. CBE3 cannot be set if CBE2 or CBE4 is set. * Bit 1 - CBE2: Cell Balancing Enable 2 When this bit is set, the integrated Cell Balancing FET between terminals PV2 and PV1 will be enabled. When the bit is cleared, the Cell Balancing FET will be disabled. The Cell Balancing FETs are always disabled in Power-off mode. CBE2 cannot be set if CBE1 or CBE3 is set. * Bit 0 - CBE1: Cell Balancing Enable 1 When this bit is set (one), the integrated Cell Balancing FET between terminals PV1 and NV will be enabled. When the bit is cleared (zero), the Cell Balancing FET will be disabled. The Cell Balancing FETs are always disabled in Power-off mode. CBE1 cannot be set if CBE2 is set.
155
8042A-AVR-07/09
ATmega16HVB/32HVB
27. 2-wire Serial Interface
27.1 Features
* * * * * * * * * *
Simple yet Powerful and Flexible Communication Interface, Only Two Bus Lines Needed Both Master and Slave Operation Supported Device can Operate as Transmitter or Receiver 7-bit Address Space allows up to 128 Different Slave Addresses Multi-master Arbitration Support Supports SM Bus transfer speeds from 10 to 100kHz Slew-rate Limited Output Drivers Noise Suppression Circuitry Rejects Spikes on Bus Lines Fully Programmable Slave Address with General Call Support Address Recognition Causes Wake-up when AVR is in Sleep Mode
27.2
Two-wire Serial Interface Bus Definition
The Two-wire Serial Interface (TWI) is ideally suited for typical microcontroller applications. The TWI protocol allows the systems designer to interconnect up to 128 different devices using only two bi-directional bus lines, one for clock (SCL) and one for data (SDA). The only external hardware needed to implement the bus is a single pull-up resistor for each of the TWI bus lines. All devices connected to the bus have individual addresses, and mechanisms for resolving bus contention are inherent in the TWI protocol. When the TWI is not used, power consumption can be minimized by writing the PRTWI bit in PRR0 to one. See "PRR0 - Power Reduction Register 0" on page 40 for details on how to use the PRTWI bit. Figure 27-1. TWI Bus Interconnection
VBUS
Device 1
Device 2
Device 3
........
Device n
R1
R2
SDA
SCL
156
8042A-AVR-07/09
ATmega16HVB/32HVB
27.2.1 TWI Terminology The following definitions are frequently encountered in this section. Table 27-1.
Term Master Slave Transmitter Receiver
TWI Terminology
Description The device that initiates and terminates a transmission. The Master also generates the SCL clock. The device addressed by a Master. The device placing data on the bus. The device reading data from the bus.
27.2.2
Electrical Interconnection As depicted in Figure 27-1, both bus lines are connected to the positive supply voltage through pull-up resistors. The bus drivers of all TWI-compliant devices are open-drain or open-collector. This implements a wired-AND function which is essential to the operation of the interface. A low level on a TWI bus line is generated when one or more TWI devices output a zero. A high level is output when all TWI devices tri-state their outputs, allowing the pull-up resistors to pull the line high. Note that all AVR devices connected to the TWI bus must be powered in order to allow any bus operation. The number of devices that can be connected to the bus is only limited by the bus capacitance limit of 400 pF and the 7-bit slave address space. A detailed specification of the electrical characteristics of the TWI is given in "2-wire Serial Interface Characteristics" on page 235.
27.3
27.3.1
Data Transfer and Frame Format
Transferring Bits Each data bit transferred on the TWI bus is accompanied by a pulse on the clock line. The level of the data line must be stable when the clock line is high. The only exception to this rule is for generating start and stop conditions. Figure 27-2. Data Validity
SDA
SCL Data Stable Data Stable Data Change
157
8042A-AVR-07/09
ATmega16HVB/32HVB
27.3.2 START and STOP Conditions The Master initiates and terminates a data transmission. The transmission is initiated when the Master issues a START condition on the bus, and it is terminated when the Master issues a STOP condition. Between a START and a STOP condition, the bus is considered busy, and no other Master should try to seize control of the bus. A special case occurs when a new START condition is issued between a START and STOP condition. This is referred to as a REPEATED START condition, and is used when the Master wishes to initiate a new transfer without relinquishing control of the bus. After a REPEATED START, the bus is considered busy until the next STOP. This is identical to the START behavior, and therefore START is used to describe both START and REPEATED START for the remainder of this datasheet, unless otherwise noted. As depicted below, START and STOP conditions are signalled by changing the level of the SDA line when the SCL line is high. Figure 27-3. START, REPEATED START, and STOP Conditions
SDA
SCL
START
STOP START
REPEATED START
STOP
27.3.3
Address Packet Format All address packets transmitted on the TWI bus are nine bits long, consisting of seven address bits, one READ/WRITE control bit and an acknowledge bit. If the READ/WRITE bit is set, a read operation is to be performed, otherwise a write operation should be performed. When a slave recognizes that it is being addressed, it should acknowledge by pulling SDA low in the ninth SCL (ACK) cycle. If the addressed Slave is busy, or for some other reason can not service the Master's request, the SDA line should be left high in the ACK clock cycle. The Master can then transmit a STOP condition, or a REPEATED START condition to initiate a new transmission. An address packet consisting of a slave address and a READ or a WRITE bit is called SLA+R or SLA+W, respectively. The MSB of the address byte is transmitted first. Slave addresses can freely be allocated by the designer, but the address 0000 000 is reserved for a general call. When a general call is issued, all slaves should respond by pulling the SDA line low in the ACK cycle. A general call is used when a Master wishes to transmit the same message to several slaves in the system. When the general call address followed by a write bit is transmitted on the bus, all slaves set up to acknowledge the general call will pull the SDA line low in the ack cycle. The following data packets will then be received by all the slaves that acknowledged the general call. Note that transmitting the general call address followed by a Read bit is meaningless, as this would cause contention if several slaves started transmitting different data. All addresses of the format 1111 xxx should be reserved for future purposes.
158
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 27-4. Address Packet Format
Addr MSB SDA Addr LSB R/W ACK
SCL 1 START 2 7 8 9
27.3.4
Data Packet Format All data packets transmitted on the TWI bus are nine bits long, consisting of one data byte and an acknowledge bit. During a data transfer, the Master generates the clock and the START and STOP conditions, while the Receiver is responsible for acknowledging the reception. An Acknowledge (ACK) is signalled by the Receiver pulling the SDA line low during the ninth SCL cycle. If the Receiver leaves the SDA line high, a NACK is signalled. When the Receiver has received the last byte, or for some reason cannot receive any more bytes, it should inform the Transmitter by sending a NACK after the final byte. The MSB of the data byte is transmitted first. Figure 27-5. Data Packet Format
Data MSB Aggregate SDA SDA from Transmitter SDA from Receiver SCL from Master 1 SLA+R/W 2 7 Data Byte 8 9 STOP, REPEATED START, or Next Data Byte Data LSB ACK
27.3.5
Combining Address and Data Packets Into a Transmission A transmission basically consists of a START condition, a SLA+R/W, one or more data packets and a STOP condition. An empty message, consisting of a START followed by a STOP condition, is illegal. Note that the wired-ANDing of the SCL line can be used to implement handshaking between the Master and the Slave. The Slave can extend the SCL low period by pulling the SCL line low. This is useful if the clock speed set up by the Master is too fast for the Slave, or the Slave needs extra time for processing between the data transmissions. The Slave extending the SCL low period will not affect the SCL high period, which is determined by the Master. As a consequence, the Slave can reduce the TWI data transfer speed by prolonging the SCL duty cycle. Figure 27-6 shows a typical data transmission. Note that several data bytes can be transmitted between the SLA+R/W and the STOP condition, depending on the software protocol implemented by the application software.
159
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 27-6. Typical Data Transmission
Addr MSB SDA Addr LSB R/W ACK Data MSB Data LSB ACK
SCL 1 START 2 7 SLA+R/W 8 9 1 2 Data Byte 7 8 9 STOP
27.4
Multi-master Bus Systems, Arbitration and Synchronization
The TWI protocol allows bus systems with several masters. Special concerns have been taken in order to ensure that transmissions will proceed as normal, even if two or more masters initiate a transmission at the same time. Two problems arise in multi-master systems: * An algorithm must be implemented allowing only one of the masters to complete the transmission. All other masters should cease transmission when they discover that they have lost the selection process. This selection process is called arbitration. When a contending master discovers that it has lost the arbitration process, it should immediately switch to Slave mode to check whether it is being addressed by the winning master. The fact that multiple masters have started transmission at the same time should not be detectable to the slaves (i.e., the data being transferred on the bus must not be corrupted). * Different masters may use different SCL frequencies. A scheme must be devised to synchronize the serial clocks from all masters, in order to let the transmission proceed in a lockstep fashion. This will facilitate the arbitration process. The wired-ANDing of the bus lines is used to solve both these problems. The serial clocks from all masters will be wired-ANDed, yielding a combined clock with a high period equal to the one from the master with the shortest high period. The low period of the combined clock is equal to the low period of the master with the longest low period. Note that all masters listen to the SCL line, effectively starting to count their SCL high and low Time-out periods when the combined SCL line goes high or low, respectively. Figure 27-7. SCL Synchronization between Multiple Masters
TA low TA high
SCL from Master A
SCL from Master B
SCL bus Line TB low Masters Start Counting Low Period TB high Masters Start Counting High Period
160
8042A-AVR-07/09
ATmega16HVB/32HVB
Arbitration is carried out by all masters continuously monitoring the SDA line after outputting data. If the value read from the SDA line does not match the value the master had output, it has lost the arbitration. Note that a master can only lose arbitration when it outputs a high SDA value while another master outputs a low value. The losing master should immediately go to Slave mode, checking if it is being addressed by the winning master. The SDA line should be left high, but losing masters are allowed to generate a clock signal until the end of the current data or address packet. Arbitration will continue until only one master remains, and this may take many bits. If several masters are trying to address the same slave, arbitration will continue into the data packet. Figure 27-8. Arbitration between Two Masters
START SDA from Master A Master A Loses Arbitration, SDA A SDA
SDA from Master B
SDA Line
Synchronized SCL Line
Note that arbitration is not allowed between: * A REPEATED START condition and a data bit. * A STOP condition and a data bit. * A REPEATED START and a STOP condition. It is the user software's responsibility to ensure that these illegal arbitration conditions never occur. This implies that in multi-master systems, all data transfers must use the same composition of SLA+R/W and data packets. In other words: All transmissions must contain the same number of data packets, otherwise the result of the arbitration is undefined.
161
8042A-AVR-07/09
ATmega16HVB/32HVB
27.5 Overview of the TWI Module
The TWI module is comprised of several submodules, as shown in Figure 27-9. The shaded registers are accessible through the AVR data bus. Figure 27-9. Overview of the TWI Module
SCL
Slew-rate Control Spike Filter
SDA
Slew-rate Control Spike Filter
Bus Interface Unit
START / STOP Control Spike Suppression
Bit Rate Generator
Prescaler
Arbitration Detection
Address/Data Shift Register (TWDR)
Ack
Bit Rate Register (TWBR)
Address Match Unit
Address Register (TWAR)
Control Unit
Status Register (TWSR) Control Register (TWCR)
Address Comparator
State Machine and Status Control
27.5.1
SCL and SDA Pins These pins interface the AVR TWI with the rest of the MCU system. The output drivers contain a slew-rate limiter in order to conform to the TWI specification. The input stages contain a spike suppression unit removing spikes shorter than 50 ns.
TWI Unit
162
8042A-AVR-07/09
ATmega16HVB/32HVB
27.5.2 Bit Rate Generator Unit This unit controls the period of SCL when operating in a Master mode. The SCL period is controlled by settings in the TWI Bit Rate Register (TWBR) and the Prescaler bits in the TWI Status Register (TWSR). Slave operation does not depend on Bit Rate or Prescaler settings, but the CPU clock frequency in the slave must be at least 16 times higher than the SCL frequency. Note that slaves may prolong the SCL low period, thereby reducing the average TWI bus clock period. The SCL frequency is generated according to the following equation: TWI Clock frequency SCL frequency = ---------------------------------------------------------TWPS 16 + 2(TWBR) 4 * TWBR = Value of the TWI Bit Rate Register. * TWPS = Value of the prescaler bits in the TWI Status Register.
Note: The TWI clock is synchronous to the CPU.
27.5.3
Bus Interface Unit This unit contains the Data and Address Shift Register (TWDR), a START/STOP Controller and Arbitration detection hardware. The TWDR contains the address or data bytes to be transmitted, or the address or data bytes received. In addition to the 8-bit TWDR, the Bus Interface Unit also contains a register containing the (N)ACK bit to be transmitted or received. This (N)ACK Register is not directly accessible by the application software. However, when receiving, it can be set or cleared by manipulating the TWI Control Register (TWCR). When in Transmitter mode, the value of the received (N)ACK bit can be determined by the value in the TWSR. The START/STOP Controller is responsible for generation and detection of START, REPEATED START, and STOP conditions. The START/STOP controller is able to detect START and STOP conditions even when the AVR MCU is in one of the sleep modes, enabling the MCU to wake up if addressed by a Master. If the TWI has initiated a transmission as Master, the Arbitration Detection hardware continuously monitors the transmission trying to determine if arbitration is in process. If the TWI has lost an arbitration, the Control Unit is informed. Correct action can then be taken and appropriate status codes generated.
27.5.4
Address Match Unit The Address Match unit checks if received address bytes match the 7-bit address in the TWI Address Register (TWAR). If the TWI General Call Recognition Enable (TWGCE) bit in the TWAR is written to one, all incoming address bits will also be compared against the General Call address. Upon an address match, the Control unit is informed, allowing correct action to be taken. The TWI may or may not acknowledge its address, depending on settings in the TWCR. The Address Match unit is able to compare addresses even when the AVR MCU is in sleep mode, enabling the MCU to wake-up if addressed by a Master.
163
8042A-AVR-07/09
ATmega16HVB/32HVB
27.5.5 Control Unit The Control unit monitors the TWI bus and generates responses corresponding to settings in the TWI Control Register (TWCR). When an event requiring the attention of the application occurs on the TWI bus, the TWI Interrupt Flag (TWINT) is asserted. In the next clock cycle, the TWI Status Register (TWSR) is updated with a status code identifying the event. The TWSR only contains relevant status information when the TWI interrupt flag is asserted. At all other times, the TWSR contains a special status code indicating that no relevant status information is available. As long as the TWINT flag is set, the SCL line is held low. This allows the application software to complete its tasks before allowing the TWI transmission to continue. The TWINT flag is set in the following situations: * After the TWI has transmitted a START/REPEATED START condition. * After the TWI has transmitted SLA+R/W. * After the TWI has transmitted an address byte. * After the TWI has lost arbitration. * After the TWI has been addressed by own slave address or general call. * After the TWI has received a data byte. * After a STOP or REPEATED START has been received while still addressed as a Slave. * When a bus error has occurred due to an illegal START or STOP condition.
164
8042A-AVR-07/09
ATmega16HVB/32HVB
27.6 Using the TWI
The AVR TWI is byte-oriented and interrupt based. Interrupts are issued after all bus events, like reception of a byte or transmission of a START condition. Because the TWI is interrupt-based, the application software is free to carry on other operations during a TWI byte transfer. Note that the TWI Interrupt Enable (TWIE) bit in TWCR together with the Global Interrupt Enable bit in SREG allow the application to decide whether or not assertion of the TWINT flag should generate an interrupt request. If the TWIE bit is cleared, the application must poll the TWINT flag in order to detect actions on the TWI bus. When the TWINT flag is asserted, the TWI has finished an operation and awaits application response. In this case, the TWI Status Register (TWSR) contains a value indicating the current state of the TWI bus. The application software can then decide how the TWI should behave in the next TWI bus cycle by manipulating the TWCR and TWDR registers. Figure 27-10 is a simple example of how the application can interface to the TWI hardware. In this example, a Master wishes to transmit a single data byte to a Slave. This description is quite abstract, a more detailed explanation follows later in this section. A simple code example implementing the desired behavior is also presented. Figure 27-10. Interfacing the Application to the TWI in a Typical Transmission
1. Application writes to TWCR to initiate transmission of START 3. Check TWSR to see if START was sent. Application loads SLA+W into TWDR, and loads appropriate control signals into TWCR, making sure that TWINT is written to one 5. Check TWSR to see if SLA+W was sent and ACK received. Application loads data into TWDR, and loads appropriate control signals into TWCR, making sure that TWINT is written to one 7. Check TWSR to see if data was sent and ACK received. Application loads appropriate control signals to send STOP into TWCR, making sure that TWINT is written to one
Application Action
TWI bus
START
SLA+W
A
Data
A
STOP
TWI Hardware Action
2. TWINT set. Status code indicates START condition sent
4. TWINT set. Status code indicates SLA+W sent, ACK received
6. TWINT set. Status code indicates data sent, ACK received
Indicates TWINT set
1. The first step in a TWI transmission is to transmit a START condition. This is done by writing a specific value into TWCR, instructing the TWI hardware to transmit a START condition. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the START condition. 2. When the START condition has been transmitted, the TWINT flag in TWCR is set, and TWSR is updated with a status code indicating that the START condition has successfully been sent. 3. The application software should now examine the value of TWSR, to make sure that the START condition was successfully transmitted. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must load SLA+W into TWDR. Remember 165
8042A-AVR-07/09
ATmega16HVB/32HVB
that TWDR is used both for address and data. After TWDR has been loaded with the desired SLA+W, a specific value must be written to TWCR, instructing the TWI hardware to transmit the SLA+W present in TWDR. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the address packet. 4. When the address packet has been transmitted, the TWINT flag in TWCR is set, and TWSR is updated with a status code indicating that the address packet has successfully been sent. The status code will also reflect whether a slave acknowledged the packet or not. 5. The application software should now examine the value of TWSR, to make sure that the address packet was successfully transmitted, and that the value of the ACK bit was as expected. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must load a data packet into TWDR. Subsequently, a specific value must be written to TWCR, instructing the TWI hardware to transmit the data packet present in TWDR. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the data packet. 6. When the data packet has been transmitted, the TWINT flag in TWCR is set, and TWSR is updated with a status code indicating that the data packet has successfully been sent. The status code will also reflect whether a slave acknowledged the packet or not. 7. The application software should now examine the value of TWSR, to make sure that the data packet was successfully transmitted, and that the value of the ACK bit was as expected. If TWSR indicates otherwise, the application software might take some special action, like calling an error routine. Assuming that the status code is as expected, the application must write a specific value to TWCR, instructing the TWI hardware to transmit a STOP condition. Which value to write is described later on. However, it is important that the TWINT bit is set in the value written. Writing a one to TWINT clears the flag. The TWI will not start any operation as long as the TWINT bit in TWCR is set. Immediately after the application has cleared TWINT, the TWI will initiate transmission of the STOP condition. Note that TWINT is NOT set after a STOP condition has been sent. Even though this example is simple, it shows the principles involved in all TWI transmissions. These can be summarized as follows: * When the TWI has finished an operation and expects application response, the TWINT flag is set. The SCL line is pulled low until TWINT is cleared. * When the TWINT flag is set, the user must update all TWI registers with the value relevant for the next TWI bus cycle. As an example, TWDR must be loaded with the value to be transmitted in the next bus cycle. * After all TWI Register updates and other pending application software tasks have been completed, TWCR is written. When writing TWCR, the TWINT bit should be set. Writing a one to TWINT clears the flag. The TWI will then commence executing whatever operation was specified by the TWCR setting. In the following an assembly and C implementation of the example is given. Note that the code below assumes that several definitions have been made for example by using include-files.
166
8042A-AVR-07/09
ATmega16HVB/32HVB
Assembly code example(1) ldi r16, (1<C example(1) TWCR = (1<Comments
Send START condition
while (!(TWCR & (1<if ((TWSR & 0xF8) != START) ERROR();
TWDR = SLA_W; TWCR = (1<while (!(TWCR & (1<if ((TWSR & 0xF8) != MT_SLA_ACK) ERROR();
TWDR = DATA; TWCR = (1<while (!(TWCR & (1<Wait for TWINT flag set. This indicates that the DATA has been transmitted, and ACK/NACK has been received. Check value of TWI Status Register. Mask prescaler bits. If status different from MT_DATA_ACK go to ERROR
if ((TWSR & 0xF8) != MT_DATA_ACK) ERROR();
TWCR = (1<1. See "About Code Examples" on page 8.
167
8042A-AVR-07/09
ATmega16HVB/32HVB
27.7 Transmission Modes
The TWI can operate in one of four major modes. These are named Master Transmitter (MT), Master Receiver (MR), Slave Transmitter (ST) and Slave Receiver (SR). Several of these modes can be used in the same application. As an example, the TWI can use MT mode to write data into a TWI EEPROM, MR mode to read the data back from the EEPROM. If other masters are present in the system, some of these might transmit data to the TWI, and then SR mode would be used. It is the application software that decides which modes are legal. The following sections describe each of these modes. Possible status codes are described along with figures detailing data transmission in each of the modes. These figures contain the following abbreviations:
S: Rs: R: W: A: A: Data: P: SLA:
START condition REPEATED START condition Read bit (high level at SDA) Write bit (low level at SDA) Acknowledge bit (low level at SDA) Not acknowledge bit (high level at SDA) 8-bit data byte STOP condition Slave Address
In Figure 27-12 on page 171 to Figure 27-18 on page 180, circles are used to indicate that the TWINT flag is set. The numbers in the circles show the status code held in TWSR, with the prescaler bits masked to zero. At these points, actions must be taken by the application to continue or complete the TWI transfer. The TWI transfer is suspended until the TWINT flag is cleared by software. When the TWINT flag is set, the status code in TWSR is used to determine the appropriate software action. For each status code, the required software action and details of the following serial transfer are given in Table 27-2 on page 170 to Table 27-5 on page 179. Note that the prescaler bits are masked to zero in these tables. 27.7.1 Master Transmitter Mode In the Master Transmitter mode, a number of data bytes are transmitted to a slave receiver (see Figure 27-11 on page 169). In order to enter a Master mode, a START condition must be transmitted. The format of the following address packet determines whether Master Transmitter or Master Receiver mode is to be entered. If SLA+W is transmitted, MT mode is entered, if SLA+R is transmitted, MR mode is entered. All the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero.
168
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 27-11. Data Transfer in Master Transmitter Mode
VBUS
Device 1
MASTER TRANSMITTER
Device 2
SLAVE RECEIVER
Device 3
........
Device n
R1
R2
SDA
SCL
A START condition is sent by writing the following value to TWCR:
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE
Value
1
X
1
0
X
1
0
X
TWEN must be set to enable the Two-wire Serial Interface, TWSTA must be written to one to transmit a START condition and TWINT must be written to one to clear the TWINT flag. The TWI will then test the Two-wire Serial Bus and generate a START condition as soon as the bus becomes free. After a START condition has been transmitted, the TWINT flag is set by hardware, and the status code in TWSR will be 0x08 (see Table 27-2). In order to enter MT mode, SLA+W must be transmitted. This is done by writing SLA+W to TWDR. Thereafter the TWINT bit should be cleared (by writing it to one) to continue the transfer. This is accomplished by writing the following value to TWCR:
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE
Value
1
X
0
0
X
1
0
X
When SLA+W have been transmitted and an acknowledgment bit has been received, TWINT is set again and a number of status codes in TWSR are possible. Possible status codes in Master mode are 0x18, 0x20, or 0x38. The appropriate action to be taken for each of these status codes is detailed in Table 27-2. When SLA+W has been successfully transmitted, a data packet should be transmitted. This is done by writing the data byte to TWDR. TWDR must only be written when TWINT is high. If not, the access will be discarded, and the Write Collision bit (TWWC) will be set in the TWCR Register. After updating TWDR, the TWINT bit should be cleared (by writing it to one) to continue the transfer. This is accomplished by writing the following value to TWCR:
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE
Value
1
X
0
0
X
1
0
X
This scheme is repeated until the last byte has been sent and the transfer is ended by generating a STOP condition or a repeated START condition. A STOP condition is generated by writing the following value to TWCR:
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE
Value
1
X
0
1
X
1
0
X
169
8042A-AVR-07/09
ATmega16HVB/32HVB
A REPEATED START condition is generated by writing the following value to TWCR:
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE
Value
1
X
1
0
X
1
0
X
After a repeated START condition (state 0x10) the Two-wire Serial Interface can access the same slave again, or a new slave without transmitting a STOP condition. Repeated START enables the master to switch between slaves, Master Transmitter mode and Master Receiver mode without losing control of the bus.
Table 27-2.
Status Code (TWSR) Prescaler Bits are 0 0x08 0x10
Status Codes for Master Transmitter Mode
Application Software Response Status of the Two-wire Serial Bus and Two-wire Serial Interface Hardware A START condition has been transmitted A repeated START condition has been transmitted To TWCR To/from TWDR Load SLA+W Load SLA+W or Load SLA+R STA X X X 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 STO 0 0 0 0 0 1 1 0 0 1 1 0 0 1 1 0 0 1 1 0 0 TWINT 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 TWEA X X X X X X X X X X X X X X X X X X X X X Next Action Taken by TWI Hardware SLA+W will be transmitted; ACK or NOT ACK will be received SLA+W will be transmitted; ACK or NOT ACK will be received SLA+R will be transmitted; Logic will switch to Master Receiver mode Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO flag will be reset Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO flag will be reset Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO flag will be reset Data byte will be transmitted and ACK or NOT ACK will be received Repeated START will be transmitted STOP condition will be transmitted and TWSTO flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO flag will be reset Two-wire Serial Bus will be released and not addressed slave mode entered A START condition will be transmitted when the bus becomes free
0x18
SLA+W has been transmitted; ACK has been received
Load data byte or No TWDR action or No TWDR action or No TWDR action
0x20
SLA+W has been transmitted; NOT ACK has been received
Load data byte or No TWDR action or No TWDR action or No TWDR action
0x28
Data byte has been transmitted; ACK has been received
Load data byte or No TWDR action or No TWDR action or No TWDR action
0x30
Data byte has been transmitted; NOT ACK has been received
Load data byte or No TWDR action or No TWDR action or No TWDR action
0x38
Arbitration lost in SLA+W or data bytes
No TWDR action or No TWDR action
170
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 27-12. Formats and States in the Master Transmitter Mode
MT
Successfull transmission to a slave receiver
S
SLA
W
A
DATA
A
P
$08
Next transfer started with a repeated start condition
$18
$28
RS
SLA
W
$10
Not acknowledge received after the slave address
A
P
R
$20
MR
Not acknowledge received after a data byte
A
P
$30
Arbitration lost in slave address or data byte
A or A
Other master continues
A or A
Other master continues
$38
Arbitration lost and addressed as slave
$38
Other master continues
A
$68
$78
$B0
To corresponding states in slave mode
From master to slave
DATA
A
Any number of data bytes and their associated acknowledge bits This number (contained in TWSR) corresponds to a defined state of the Two-wire Serial Bus. The prescaler bits are zero or masked to zero
From slave to master
n
171
8042A-AVR-07/09
ATmega16HVB/32HVB
27.7.2 Master Receiver Mode In the Master Receiver mode, a number of data bytes are received from a slave transmitter (see Figure 27-13). In order to enter a Master mode, a START condition must be transmitted. The format of the following address packet determines whether Master Transmitter or Master Receiver mode is to be entered. If SLA+W is transmitted, MT mode is entered, if SLA+R is transmitted, MR mode is entered. All the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. Figure 27-13. Data Transfer in Master Receiver Mode
VBUS
Device 1
MASTER RECEIVER
Device 2
SLAVE TRANSMITTER
Device 3
........
Device n
R1
R2
SDA
SCL
A START condition is sent by writing the following value to TWCR:
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE
Value
1
X
1
0
X
1
0
X
TWEN must be written to one to enable the Two-wire Serial Interface, TWSTA must be written to one to transmit a START condition and TWINT must be set to clear the TWINT flag. The TWI will then test the Two-wire Serial Bus and generate a START condition as soon as the bus becomes free. After a START condition has been transmitted, the TWINT flag is set by hardware, and the status code in TWSR will be 0x08 (see Table 27-2 on page 170). In order to enter MR mode, SLA+R must be transmitted. This is done by writing SLA+R to TWDR. Thereafter the TWINT bit should be cleared (by writing it to one) to continue the transfer. This is accomplished by writing the following value to TWCR:
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE
Value
1
X
0
0
X
1
0
X
When SLA+R have been transmitted and an acknowledgment bit has been received, TWINT is set again and a number of status codes in TWSR are possible. Possible status codes in Master mode are 0x38, 0x40, or 0x48. The appropriate action to be taken for each of these status codes is detailed in Table 27-12 on page 171. Received data can be read from the TWDR Register when the TWINT flag is set high by hardware. This scheme is repeated until the last byte has been received. After the last byte has been received, the MR should inform the ST by sending a NACK after the last received data byte. The transfer is ended by generating a STOP condition or a repeated START condition. A STOP condition is generated by writing the following value to TWCR:
172
8042A-AVR-07/09
ATmega16HVB/32HVB
TWCR
TWINT
TWEA
TWSTA
TWSTO
TWWC
TWEN
-
TWIE
Value
1
X
0
1
X
1
0
X
A REPEATED START condition is generated by writing the following value to TWCR:
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE
Value
1
X
1
0
X
1
0
X
After a repeated START condition (state 0x10) the Two-wire Serial Interface can access the same slave again, or a new slave without transmitting a STOP condition. Repeated START enables the master to switch between slaves, Master Transmitter mode and Master Receiver mode without losing control over the bus. Table 27-3.
Status Code (TWSR) Prescaler Bits are 0 0x08 0x10
Status Codes for Master Receiver Mode
Application Software Response Status of the Two-wire Serial Bus and Two-wire Serial Interface Hardware A START condition has been transmitted A repeated START condition has been transmitted To TWCR To/from TWDR Load SLA+R Load SLA+R or Load SLA+W STA X X X 0 1 0 0 1 0 1 0 0 1 0 1 STO 0 0 0 0 0 0 0 0 1 1 0 0 0 1 1 TWINT 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 TWEA X X X X X 0 1 X X X 0 1 X X X Next Action Taken by TWI Hardware SLA+R will be transmitted ACK or NOT ACK will be received SLA+R will be transmitted ACK or NOT ACK will be received SLA+W will be transmitted Logic will switch to Master Transmitter mode Two-wire Serial Bus will be released and not addressed Slave mode will be entered A START condition will be transmitted when the bus becomes free Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Repeated START will be transmitted STOP condition will be transmitted and TWSTO flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO flag will be reset Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Repeated START will be transmitted STOP condition will be transmitted and TWSTO flag will be reset STOP condition followed by a START condition will be transmitted and TWSTO flag will be reset
0x38
Arbitration lost in SLA+R or NOT ACK bit
No TWDR action or No TWDR action
0x40
SLA+R has been transmitted; ACK has been received SLA+R has been transmitted; NOT ACK has been received
No TWDR action or No TWDR action
0x48
No TWDR action or No TWDR action or No TWDR action
0x50
Data byte has been received; ACK has been returned Data byte has been received; NOT ACK has been returned
Read data byte or Read data byte
0x58
Read data byte or Read data byte or Read data byte
173
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 27-14. Formats and States in the Master Receiver Mode
MR
Successfull reception from a slave receiver
S
SLA
R
A
DATA
A
DATA
A
P
$08
Next transfer started with a repeated start condition
$40
$50
$58
RS
SLA
R
$10
Not acknowledge received after the slave address
A
P
W
$48
MT
Arbitration lost in slave address or data byte
A or A
Other master continues
A
Other master continues
$38
Arbitration lost and addressed as slave
$38
Other master continues
A
$68
$78
$B0
To corresponding states in slave mode
From master to slave
DATA
A
Any number of data bytes and their associated acknowledge bits This number (contained in TWSR) corresponds to a defined state of the Two-wire Serial Bus. The prescaler bits are zero or masked to zero
From slave to master
n
27.7.3
Slave Receiver Mode In the Slave Receiver mode, a number of data bytes are received from a master transmitter (see Figure 27-15). All the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. Figure 27-15. Data Transfer in Slave Receiver Mode
VBUS
Device 1
SLAVE RECEIVER
Device 2
MASTER TRANSMITTER
Device 3
........
Device n
R1
R2
SDA
SCL
To initiate the Slave Receiver mode, TWAR and TWCR must be initialized as follows:
174
8042A-AVR-07/09
ATmega16HVB/32HVB
TWAR
TWA6
TWA5
TWA4
TWA3
TWA2
TWA1
TWA0
TWGCE
Value
Device's Own Slave Address
The upper seven bits are the address to which the Two-wire Serial Interface will respond when addressed by a master. If the LSB is set, the TWI will respond to the general call address (0x00), otherwise it will ignore the general call address.
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE
Value
0
1
0
0
0
1
0
X
TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable the acknowledgment of the device's own slave address or the general call address. TWSTA and TWSTO must be written to zero. When TWAR and TWCR have been initialized, the TWI waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. If the direction bit is "0" (write), the TWI will operate in SR mode, otherwise ST mode is entered. After its own slave address and the write bit have been received, the TWINT flag is set and a valid status code can be read from TWSR. The status code is used to determine the appropriate software action. The appropriate action to be taken for each status code is detailed in Table 27-4. The Slave Receiver mode may also be entered if arbitration is lost while the TWI is in the Master mode (see states 0x68 and 0x78). If the TWEA bit is reset during a transfer, the TWI will return a "Not Acknowledge" ("1") to SDA after the next received data byte. This can be used to indicate that the slave is not able to receive any more bytes. While TWEA is zero, the TWI does not acknowledge its own slave address. However, the Two-wire Serial Bus is still monitored and address recognition may resume at any time by setting TWEA. This implies that the TWEA bit may be used to temporarily isolate the TWI from the Two-wire Serial Bus. In all sleep modes other than Idle mode, the clock system to the TWI is turned off. If the TWEA bit is set, the interface can still acknowledge its own slave address or the general call address by using the Two-wire Serial Bus clock as a clock source. The part will then wake-up from sleep and the TWI will hold the SCL clock low during the wake up and until the TWINT flag is cleared (by writing it to one). Further data reception will be carried out as normal, with the AVR clocks running as normal. Observe that if the AVR is set up with a long start-up time, the SCL line may be held low for a long time, blocking other data transmissions. Note that the Two-wire Serial Interface Data Register - TWDR does not reflect the last byte present on the bus when waking up from these Sleep modes.
175
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 27-4.
Status Code (TWSR) Prescaler Bits Are 0 0x60
Status Codes for Slave Receiver Mode
Application Software Response Status of the Two-wire Serial Bus and Two-wire Serial Interface Hardware Own SLA+W has been received; ACK has been returned Arbitration lost in SLA+R/W as master; own SLA+W has been received; ACK has been returned General call address has been received; ACK has been returned Arbitration lost in SLA+R/W as master; General call address has been received; ACK has been returned Previously addressed with own SLA+W; data has been received; ACK has been returned Previously addressed with own SLA+W; data has been received; NOT ACK has been returned To TWCR To/from TWDR No TWDR action or No TWDR action STA X X X X X X X X X X 0 0 STO 0 0 0 0 0 0 0 0 0 0 0 0 TWINT 1 1 1 1 1 1 1 1 1 1 1 1 TWEA 0 1 0 1 0 1 0 1 0 1 0 1 Next Action Taken by TWI Hardware Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free
0x68
No TWDR action or No TWDR action No TWDR action or No TWDR action
0x70
0x78
No TWDR action or No TWDR action Read data byte or Read data byte Read data byte or Read data byte or
0x80
0x88
Read data byte or
1
0
1
0
Read data byte
1
0
1
1
0x90
Previously addressed with general call; data has been received; ACK has been returned Previously addressed with general call; data has been received; NOT ACK has been returned
Read data byte or Read data byte Read data byte or Read data byte or
X X 0 0
0 0 0 0
1 1 1 1
0 1 0 1
0x98
Read data byte or
1
0
1
0
Read data byte
1
0
1
1
0xA0
A STOP condition or repeated START condition has been received while still addressed as slave
Read data byte or Read data byte or
0 0
0 0
1 1
0 1
Read data byte or
1
0
1
0
Read data byte
1
0
1
1
176
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 27-16. Formats and States in the Slave Receiver Mode
Reception of the own slave address and one or more data bytes. All are acknowledged
S
SLA
W
A
DATA
A
DATA
A
P or S
$60
Last data byte received is not acknowledged
$80
$80
$A0
A
P or S
$88
Arbitration lost as master and addressed as slave
A
$68
Reception of the general call address and one or more data bytes
General Call
A
DATA
A
DATA
A
P or S
$70
Last data byte received is not acknowledged
$90
$90
$A0
A
P or S
$98
Arbitration lost as master and addressed as slave by general call
A
$78
From master to slave
DATA
A
Any number of data bytes and their associated acknowledge bits This number (contained in TWSR) corresponds to a defined state of the Two-wire Serial Bus. The prescaler bits are zero or masked to zero
From slave to master
n
177
8042A-AVR-07/09
ATmega16HVB/32HVB
27.7.4 Slave Transmitter Mode In the Slave Transmitter mode, a number of data bytes are transmitted to a master receiver (see Figure 27-17). All the status codes mentioned in this section assume that the prescaler bits are zero or are masked to zero. Figure 27-17. Data Transfer in Slave Transmitter Mode
VBUS
Device 1
SLAVE TRANSMITTER
Device 2
MASTER RECEIVER
Device 3
........
Device n
R1
R2
SDA
SCL
To initiate the Slave Transmitter mode, TWAR and TWCR must be initialized as follows:
TWAR TWA6 TWA5 TWA4 TWA3 TWA2 TWA1 TWA0 TWGCE
Value
Device's Own Slave Address
The upper seven bits are the address to which the Two-wire Serial Interface will respond when addressed by a master. If the LSB is set, the TWI will respond to the general call address (0x00), otherwise it will ignore the general call address.
TWCR TWINT TWEA TWSTA TWSTO TWWC TWEN - TWIE
Value
0
1
0
0
0
1
0
X
TWEN must be written to one to enable the TWI. The TWEA bit must be written to one to enable the acknowledgment of the device's own slave address or the general call address. TWSTA and TWSTO must be written to zero. When TWAR and TWCR have been initialized, the TWI waits until it is addressed by its own slave address (or the general call address if enabled) followed by the data direction bit. If the direction bit is "1" (read), the TWI will operate in ST mode, otherwise SR mode is entered. After its own slave address and the write bit have been received, the TWINT flag is set and a valid status code can be read from TWSR. The status code is used to determine the appropriate software action. The appropriate action to be taken for each status code is detailed in Table 27-5. The Slave Transmitter mode may also be entered if arbitration is lost while the TWI is in the Master mode (see state 0xB0). If the TWEA bit is written to zero during a transfer, the TWI will transmit the last byte of the transfer. State 0xC0 or state 0xC8 will be entered, depending on whether the master receiver transmits a NACK or ACK after the final byte. The TWI is switched to the not addressed Slave mode, and will ignore the master if it continues the transfer. Thus the master receiver receives all "1" as serial data. State 0xC8 is entered if the master demands additional data bytes (by transmitting ACK), even though the slave has transmitted the last byte (TWEA zero and expecting NACK from the master).
178
8042A-AVR-07/09
ATmega16HVB/32HVB
While TWEA is zero, the TWI does not respond to its own slave address. However, the Two-wire Serial Bus is still monitored and address recognition may resume at any time by setting TWEA. This implies that the TWEA bit may be used to temporarily isolate the TWI from the Two-wire Serial Bus. In all sleep modes other than Idle mode, the clock system to the TWI is turned off. If the TWEA bit is set, the interface can still acknowledge its own slave address or the general call address by using the Two-wire Serial Bus clock as a clock source. The part will then wake up from sleep and the TWI will hold the SCL clock will low during the wake up and until the TWINT flag is cleared (by writing it to one). Further data transmission will be carried out as normal, with the AVR clocks running as normal. Observe that if the AVR is set up with a long start-up time, the SCL line may be held low for a long time, blocking other data transmissions. Note that the Two-wire Serial Interface Data Register - TWDR - does not reflect the last byte present on the bus when waking up from these sleep modes. Table 27-5.
Status Code (TWSR) Prescaler Bits are 0 0xA8
Status Codes for Slave Transmitter Mode
Application Software Response Status of the Two-wire Serial Bus and Two-wire Serial Interface Hardware Own SLA+R has been received; ACK has been returned To TWCR To/from TWDR Load data byte or Load data byte STA X X X X X X 0 0 STO 0 0 0 0 0 0 0 0 TWINT 1 1 1 1 1 1 1 1 TWEA 0 1 0 1 0 1 0 1 Next Action Taken by TWI Hardware Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; no recognition of own SLA or GCA Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1" Switched to the not addressed Slave mode; no recognition of own SLA or GCA; a START condition will be transmitted when the bus becomes free Switched to the not addressed Slave mode; own SLA will be recognized; GCA will be recognized if TWGCE = "1"; a START condition will be transmitted when the bus becomes free
0xB0
Arbitration lost in SLA+R/W as master; own SLA+R has been received; ACK has been returned Data byte in TWDR has been transmitted; ACK has been received Data byte in TWDR has been transmitted; NOT ACK has been received
Load data byte or Load data byte Load data byte or Load data byte No TWDR action or No TWDR action or
0xB8
0xC0
No TWDR action or
1
0
1
0
No TWDR action
1
0
1
1
0xC8
Last data byte in TWDR has been transmitted (TWEA = "0"); ACK has been received
No TWDR action or No TWDR action or
0 0
0 0
1 1
0 1
No TWDR action or
1
0
1
0
No TWDR action
1
0
1
1
179
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 27-18. Formats and States in the Slave Transmitter Mode
Reception of the own slave address and one or more data bytes
S
SLA
R
A
DATA
A
DATA
A
P or S
$A8
Arbitration lost as master and addressed as slave
$B8
$C0
A
$B0
Last data byte transmitted. Switched to not addressed slave (TWEA = '0')
A
All 1's
P or S
$C8
From master to slave
DATA
A
Any number of data bytes and their associated acknowledge bits This number (contained in TWSR) corresponds to a defined state of the Two-wire Serial Bus. The prescaler bits are zero or masked to zero
From slave to master
n
27.7.5
Miscellaneous States There are two status codes that do not correspond to a defined TWI state, see Table 27-6. Status 0xF8 indicates that no relevant information is available because the TWINT flag is not set. This occurs between other states, and when the TWI is not involved in a serial transfer. Status 0x00 indicates that a bus error has occurred during a Two-wire Serial Bus transfer. A bus error occurs when a START or STOP condition occurs at an illegal position in the format frame. Examples of such illegal positions are during the serial transfer of an address byte, a data byte, or an acknowledge bit. When a bus error occurs, TWINT is set. To recover from a bus error, the TWSTO flag must set and TWINT must be cleared by writing a logic one to it. This causes the TWI to enter the not addressed Slave mode and to clear the TWSTO flag (no other bits in TWCR are affected). The SDA and SCL lines are released, and no STOP condition is transmitted.
180
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 27-6.
Status Code (TWSR) Prescaler Bits are 0 0xF8 0x00
Miscellaneous States
Application Software Response Status of the Two-wire Serial Bus and Two-wire Serial Interface hardware No relevant state information available; TWINT = "0" Bus error due to an illegal START or STOP condition To TWCR To/from TWDR No TWDR action No TWDR action 0 STA STO TWINT TWEA Next Action Taken by TWI Hardware Wait or proceed current transfer X Only the internal hardware is affected, no STOP condition is sent on the bus. In all cases, the bus is released and TWSTO is cleared.
No TWCR action 1 1
27.7.6
Combining Several TWI Modes In some cases, several TWI modes must be combined in order to complete the desired action. Consider for example reading data from a serial EEPROM. Typically, such a transfer involves the following steps: 1. The transfer must be initiated. 2. The EEPROM must be instructed what location should be read. 3. The reading must be performed. 4. The transfer must be finished. Note that data is transmitted both from Master to Slave and vice versa. The Master must instruct the slave what location it wants to read, requiring the use of the MT mode. Subsequently, data must be read from the slave, implying the use of the MR mode. Thus, the transfer direction must be changed. The Master must keep control of the bus during all these steps, and the steps should be carried out as an atomic operation. If this principle is violated in a multi-master system, another master can alter the data pointer in the EEPROM between steps 2 and 3, and the master will read the wrong data location. Such a change in transfer direction is accomplished by transmitting a REPEATED START between the transmission of the address byte and reception of the data. After a REPEATED START, the master keeps ownership of the bus. The following figure shows the flow in this transfer. Figure 27-19. Combining Several TWI Modes to Access a Serial EEPROM
Master Transmitter Master Receiver
S
SLA+W
A
ADDRESS
A
Rs
SLA+R
A
DATA
A
P
S = START Transmitted from master to slave
Rs = REPEATED START Transmitted from slave to master
P = STOP
27.8
Multi-master Systems and Arbitration
If multiple masters are connected to the same bus, transmissions may be initiated simultaneously by one or more of them. The TWI standard ensures that such situations are handled in such a way that one of the masters will be allowed to proceed with the transfer, and that no data will be lost in the process. An example of an arbitration situation is depicted below, where two masters are trying to transmit data to a slave receiver.
181
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 27-20. An Arbitration Example
VBUS
Device 1
MASTER TRANSMITTER
Device 2
MASTER TRANSMITTER
Device 3
SLAVE RECEIVER
........
Device n
R1
R2
SDA
SCL
Several different scenarios may arise during arbitration, as described below: * Two or more masters are performing identical communication with the same slave. In this case, neither the slave nor any of the masters will know about the bus contention. * Two or more masters are accessing the same slave with different data or direction bit. In this case, arbitration will occur, either in the READ/WRITE bit or in the data bits. The masters trying to output a one on SDA while another master outputs a zero will lose the arbitration. Losing masters will switch to not addressed Slave mode or wait until the bus is free and transmit a new START condition, depending on application software action. * Two or more masters are accessing different slaves. In this case, arbitration will occur in the SLA bits. Masters trying to output a one on SDA while another master outputs a zero will lose the arbitration. Masters losing arbitration in SLA will switch to Slave mode to check if they are being addressed by the winning master. If addressed, they will switch to SR or ST mode, depending on the value of the READ/WRITE bit. If they are not being addressed, they will switch to not addressed Slave mode or wait until the bus is free and transmit a new START condition, depending on application software action. This is summarized in Figure 27-21. Possible status values are given in circles. Figure 27-21. Possible Status Codes Caused by Arbitration
START SLA Data STOP
Arbitration lost in SLA
Arbitration lost in Data
Own Address / General Call received
No
38
TWI bus will be released and not addressed slave mode will be entered A START condition will be transmitted when the bus becomes free
Yes Write 68/78
Data byte will be received and NOT ACK will be returned Data byte will be received and ACK will be returned
Direction
Read B0
Last data byte will be transmitted and NOT ACK should be received Data byte will be transmitted and ACK should be received
182
8042A-AVR-07/09
ATmega16HVB/32HVB
27.9 Bus Connect/Disconnect for Two-wire Serial Interface
The Bus Connect/Disconnect module is an addition to the TWI Interface. Based on a configuration bit, an interrupt can be generated either when the TWI bus is connected or disconnected. Figure 27-22 illustrates the Bus Connect/Disconnect logic, where SDA and SCL are the TWI data and clock lines, respectively. When the TWI bus is connected, both the SDA and the SCL lines will become high simultaneously. If the TWBCIP bit is cleared, the interrupt will be executed if enabled. Once the bus is connected, the TWBCIP bit should be set. This enables detection of when the bus is disconnected, and prevents repetitive interrupts every time both the SDA and SCL lines are high (e.g. bus IDLE state). When the TWI bus is disconnected, both the SDA and the SCL lines will become low simultaneously. If the TWBCIP bit is set, the interrupt will be executed if enabled and if both lines remain low for a configurable time period. By adding this time constraint, unwanted interrupts caused by both lines going low during normal bus communication is prevented. Figure 27-22. Overview of Bus Connect/Disconnect.
SCL SDA DELAY ELEMENT START DELAY OUTPUT
TWBCIP
TWBDT
SET TWBCIF
TWBCSR
IRQ
8-BIT DATA BUS
183
8042A-AVR-07/09
ATmega16HVB/32HVB
27.10 Register Description
27.10.1 TWBR - TWI Bit Rate Register
Bit (0xB8) Read/Write Initial Value 7
TWBR7
6
TWBR6
5
TWBR5
4
TWBR4
3
TWBR3
2
TWBR2
1
TWBR1
0
TWBR0 TWBR
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
* Bits 7:0 - TWI Bit Rate Register TWBR selects the division factor for the bit rate generator. The bit rate generator is a frequency divider which generates the SCL clock frequency in the Master modes. See "Bit Rate Generator Unit" on page 163 for calculating bit rates. 27.10.2 TWCR - TWI Control Register
Bit (0xBC) Read/Write Initial Value 7
TWINT
6
TWEA
5
TWSTA
4
TWSTO
3
TWWC
2
TWEN
1
-
0
TWIE TWCR
R/W 0
R/W 0
R/W 0
R/W 0
R 0
R/W 0
R 0
R/W 0
The TWCR is used to control the operation of the TWI. It is used to enable the TWI, to initiate a Master access by applying a START condition to the bus, to generate a Receiver acknowledge, to generate a stop condition, and to control halting of the bus while the data to be written to the bus are written to the TWDR. It also indicates a write collision if data is attempted written to TWDR while the register is inaccessible. * Bit 7 - TWINT: TWI Interrupt Flag This bit is set by hardware when the TWI has finished its current job and expects application software response. If the I-bit in SREG and TWIE in TWCR are set, the MCU will jump to the TWI Interrupt Vector. While the TWINT flag is set, the SCL low period is stretched. The TWINT flag must be cleared by software by writing a logic one to it. Note that this flag is not automatically cleared by hardware when executing the interrupt routine. Also note that clearing this flag starts the operation of the TWI, so all accesses to the TWI Address Register (TWAR), TWI Status Register (TWSR), and TWI Data Register (TWDR) must be complete before clearing this flag. * Bit 6 - TWEA: TWI Enable Acknowledge Bit The TWEA bit controls the generation of the acknowledge pulse. If the TWEA bit is written to one, the ACK pulse is generated on the TWI bus if the following conditions are met: 1. The device's own slave address has been received. 2. A general call has been received, while the TWGCE bit in the TWAR is set. 3. A data byte has been received in Master Receiver or Slave Receiver mode. By writing the TWEA bit to zero, the device can be virtually disconnected from the Two-wire Serial Bus temporarily. Address recognition can then be resumed by writing the TWEA bit to one again. * Bit 5 - TWSTA: TWI START Condition Bit The application writes the TWSTA bit to one when it desires to become a Master on the Twowire Serial Bus. The TWI hardware checks if the bus is available, and generates a START con-
184
8042A-AVR-07/09
ATmega16HVB/32HVB
dition on the bus if it is free. However, if the bus is not free, the TWI waits until a STOP condition is detected, and then generates a new START condition to claim the Bus Master status. TWSTA is cleared by the TWI hardware when the START condition has been transmitted. * Bit 4 - TWSTO: TWI STOP Condition Bit Writing the TWSTO bit to one in Master mode will generate a STOP condition on the Two-wire Serial Bus. When the STOP condition is executed on the bus, the TWSTO bit is cleared automatically. In Slave mode, setting the TWSTO bit can be used to recover from an error condition. This will not generate a STOP condition, but the TWI returns to a well-defined unaddressed Slave mode and releases the SCL and SDA lines to a high impedance state. * Bit 3 - TWWC: TWI Write Collision Flag The TWWC bit is set when attempting to write to the TWI Data Register - TWDR when TWINT is low. This flag is cleared by writing the TWDR Register when TWINT is high. * Bit 2 - TWEN: TWI Enable Bit The TWEN bit enables TWI operation and activates the TWI interface. When TWEN is written to one, the TWI takes control over the I/O pins connected to the SCL and SDA pins, enabling the slew-rate limiters and spike filters. If this bit is written to zero, the TWI is switched off and all TWI transmissions are terminated, regardless of any ongoing operation. * Bit 1 - Res: Reserved Bit This bit is a reserved bit and will always read as zero. * Bit 0 - TWIE: TWI Interrupt Enable When this bit is written to one, and the I-bit in SREG is set, the TWI interrupt request will be activated for as long as the TWINT flag is high. 27.10.3 TWSR - TWI Status Register
Bit (0xB9) Read/Write Initial Value 7
TWS7
6
TWS6
5
TWS5
4
TWS4
3
TWS3
2
-
1
TWPS1
0
TWPS0 TWSR
R 1
R 1
R 1
R 1
R 1
R 0
R/W 0
R/W 0
* Bits 7:3 - TWS: TWI Status These five bits reflect the status of the TWI logic and the Two-wire Serial Bus. The different status codes are described in Table 27-2 on page 170 through Table 27-5 on page 179. Note that the value read from TWSR contains both the 5-bit status value and the 2-bit prescaler value. The application designer should mask the prescaler bits to zero when checking the status bits. This makes status checking independent of prescaler setting. This approach is used in this datasheet, unless otherwise noted. * Bit 2 - Res: Reserved Bit This bit is reserved and will always read as zero. * Bits 1:0 - TWPS: TWI Prescaler Bits These bits can be read and written, and control the bit rate prescaler.
185
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 27-7.
TWI Bit Rate Prescaler
TWPS0 0 1 0 1 Prescaler Value 1 4 16 64
TWPS1 0 0 1 1
To calculate bit rates, see "Bit Rate Generator Unit" on page 163. The value of TWPS1:0 is used in the equation. 27.10.4 TWDR - TWI Data Register
Bit (0xBB) Read/Write Initial Value 7
TWD7
6
TWD6
5
TWD5
4
TWD4
3
TWD3
2
TWD2
1
TWD1
0
TWD0 TWDR
R/W 1
R/W 1
R/W 1
R/W 1
R/W 1
R/W 1
R/W 1
R/W 1
In Transmit mode, TWDR contains the next byte to be transmitted. In Receive mode, the TWDR contains the last byte received. It is writable while the TWI is not in the process of shifting a byte. This occurs when the TWI Interrupt Flag (TWINT) is set by hardware. Note that the data register cannot be initialized by the user before the first interrupt occurs. The data in TWDR remains stable as long as TWINT is set. While data is shifted out, data on the bus is simultaneously shifted in. TWDR always contains the last byte present on the bus, except after a wake-up from a sleep mode by the TWI interrupt. In this case, the contents of TWDR is undefined. In the case of a lost bus arbitration, no data is lost in the transition from Master to Slave. Handling of the ACK bit is controlled automatically by the TWI logic, the CPU cannot access the ACK bit directly. * Bits 7:0 - TWD: TWI Data Register These eight bits constitute the next data byte to be transmitted, or the latest data byte received on the Two-wire Serial Bus. 27.10.5 TWAR - TWI (Slave) Address Register
Bit (0xBA) Read/Write Initial Value 7
TWA6
6
TWA5
5
TWA4
4
TWA3
3
TWA2
2
TWA1
1
TWA0
0
TWGCE TWAR
R/W 1
R/W 1
R/W 1
R/W 1
R/W 1
R/W 1
R/W 1
R/W 0
The TWAR should be loaded with the 7-bit slave address (in the seven most significant bits of TWAR) to which the TWI will respond when programmed as a slave transmitter or Receiver, and not needed in the Master modes. In multi-master systems, TWAR must be set in masters which can be addressed as slaves by other masters. The LSB of TWAR is used to enable recognition of the general call address (0x00). There is an associated address comparator that looks for the slave address (or general call address if enabled) in the received serial address. If a match is found, an interrupt request is generated. * Bits 7:1 - TWA: TWI (Slave) Address Register These seven bits constitute the slave address of the TWI unit.
186
8042A-AVR-07/09
ATmega16HVB/32HVB
* Bit 0 - TWGCE: TWI General Call Recognition Enable Bit If set, this bit enables the recognition of a General Call given over the Two-wire Serial Bus. 27.10.6 TWAMR - TWI (Slave) Address Mask Register
Bit (0xBD) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4
TWAM[6:0]
3
2
1
0
- TWAMR
R/W 0
R/W 0
R/W 0
R/W 0
R 0
* Bits 7:1 - TWAM: TWI Address Mask The TWAMR can be loaded with a 7-bit Slave Address mask. Each of the bits in TWAMR can mask (disable) the corresponding address bits in the TWI Address Register (TWAR). If the mask bit is set to one then the address match logic ignores the compare between the incoming address bit and the corresponding bit in TWAR. Figure 27-23 shown the address match logic in detail. Figure 27-23. TWI Address Match Logic, Block Diagram
TWAR0 Address Bit 0 TWAMR0 Address Bit Comparator 0 Address Match
Address Bit Comparator 6..1
* Bit 0 - Res: Reserved Bit This bit is an unused bit in the ATmega16HVB/32HVB, and will always read as zero. 27.10.7 TWBCSR - TWI Bus Control and Status Register
Bit (0xBE) Read/Write Initial Value 7
TWBCIF
6
TWBCIE
5
-
4
-
3
-
2
TWBDT1
1
TWBDT0
0
TWBCIP TWBCSR
R/W
X
R/W 0
R 0
R 0
R 0
R/W 0
R/W 0
R/W 0
* Bit 7 - TWBCIF: TWI Bus Connect/Disconnect Interrupt Flag Based on the TWBCIP bit, the TWBCIF bit is set when the TWI bus is connected or disconnected(1). TWBCIF is cleared by hardware when executing the corresponding interrupt handling vector. Alternatively, TWBCIF is cleared by writing a logic one to the flag. When the SREG I-bit, TWBCIE (TWI Bus Connect/Disconnect Interrupt Enable), and TWBCIF are set, the TWI Bus Connect/Disconnect Interrupt is executed. If both SDA and SCL are high during reset, TWBCIF will be set after reset. Otherwise TWBCIF will be cleared after reset.
Note: 1. The TWEN bit in the TWCR register must be set for the Bus Connect/Disconnect feature to be enabled.
187
8042A-AVR-07/09
ATmega16HVB/32HVB
* Bit 6 - TWBCIE: TWI Bus Connect/Disconnect Interrupt Enable When the TWBCIE bit and the I-bit in the Status Register are set, the TWI Bus Connect/Disconne ct In terr upt is e nab le d. Th e corre spon ding inte rrup t is execu ted if a TWI Bus Connect/Disconnect occurs, i.e., when the TWBCIE bit is set. * Bit 5:3 - Res: Reserved Bits These bits are reserved bits in the ATmega16HVB/32HVB and will always read as zero. * Bit 2:1 - TWBDT1, TWBDT0: TWI Bus Disconnect Time-out Period The TWBDT bits decides how long both the TWI data (SDA) and clock (SCL) signals must be low before generating the TWI Bus Disconnect Interrupt. The different configuration values and their corresponding time-out periods are shown in Table 27-8.
Table 27-8.
TWBDT1 0 0 1 1
TW Bus Disconnect Time-out Period
TWBDT0 0 1 0 1 TWI Bus Disconnect Time-out Period 250 ms 500 ms 1000 ms 2000 ms
* Bit 0 - TWBCIP: TWI Bus Connect/Disconnect Interrupt Polarity The TWBCIP bit decide if the TWI Bus Connect/Disconnect Interrupt Flag (TWBCIF) should be set on a Bus Connect or a Bus Disconnect. If TWBCIP is cleared, the TWBCIF flag is set on a Bus Connect. If TWBCIP is set, the TWBCIF flag is set on a Bus Disconnect.
188
8042A-AVR-07/09
ATmega16HVB/32HVB
28. debugWIRE On-chip Debug System
28.1 Features
* * * * * * * * * *
Complete Program Flow Control Emulates All On-chip Functions, Both Digital and Analog, except RESET Pin Real-time Operation Symbolic Debugging Support (Both at C and Assembler Source Level, or for Other HLLs) Unlimited Number of Program Break Points (Using Software Break Points) Non-intrusive Operation Electrical Characteristics Identical to Real Device Automatic Configuration System High-Speed Operation Programming of Non-volatile Memories
28.2
Overview
The debugWIRE On-chip debug system uses a One-wire, bi-directional interface to control the program flow, execute AVR instructions in the CPU and to program the different non-volatile memories.
28.3
Physical Interface
When the debugWIRE Enable (DWEN) Fuse is programmed and Lock bits are unprogrammed, the debugWIRE system within the target device is activated. The RESET port pin is configured as a wire-AND (open-drain) bi-directional I/O pin with pull-up enabled and becomes the communication gateway between target and emulator. Figure 28-1. The debugWIRE Setup
3.0 - 5.5V 1.8
VCC
dW
dW(RESET)
GND
Figure 28-1 shows the schematic of a target MCU, with debugWIRE enabled, and the emulator connector. The system clock is not affected by debugWIRE and will always be the clock source selected by the OSCSEL Fuses.
189
8042A-AVR-07/09
ATmega16HVB/32HVB
When designing a system where debugWIRE will be used, the following observations must be made for correct operation: * Pull-up resistors on the dW/(RESET) line must not be smaller than 10k. The pull-up resistor is not required for debugWIRE functionality. * Connecting the RESET pin directly to VCC will not work. * Capacitors connected to the RESET pin must be disconnected when using debugWire. * All external reset sources must be disconnected.
28.4
Software Break Points
debugWIRE supports Program memory Break Points by the AVR Break instruction. Setting a Break Point in AVR Studio(R) will insert a BREAK instruction in the Program memory. The instruction replaced by the BREAK instruction will be stored. When program execution is continued, the stored instruction will be executed before continuing from the Program memory. A break can be inserted manually by putting the BREAK instruction in the program. The Flash must be re-programmed each time a Break Point is changed. This is automatically handled by AVR Studio through the debugWIRE interface. The use of Break Points will therefore reduce the Flash Data retention. Devices used for debugging purposes should not be shipped to end customers.
28.5
Limitations of debugWIRE
The debugWIRE communication pin (dW) is physically located on the same pin as External Reset (RESET). An External Reset source is therefore not supported when the debugWIRE is enabled. A programmed DWEN Fuse enables some parts of the clock system to be running in all sleep modes. This will increase the power consumption while in sleep. Thus, the DWEN Fuse should be disabled when debugWire is not used. When using debugWIRE to access the flash (reading/writing), one must make sure the SPMCSR register is not locked from before. If SPMCSR is locked the result of the operation may not be as expected.
28.6
Register Description
The following section describes the registers used with the debugWire.
28.6.1
DWDR - debugWire Data Register
Bit 0x31 (0x51) Read/Write Initial Value R/W 0 R/W 0 R/W 0 7 6 5 4 3 2 1 0 DWDR R/W 0 R/W 0 R/W 0
DWDR[7:0] R/W 0 R/W 0
The DWDR Register provides a communication channel from the running program in the MCU to the debugger. This register is only accessible by the debugWIRE and can therefore not be used as a general purpose register in the normal operations.
190
8042A-AVR-07/09
ATmega16HVB/32HVB
29. Boot Loader Support - Read-While-Write Self-Programming
29.1 Features
* * * * * * *
Read-While-Write Self-Programming Flexible Boot Memory Size High Security (Separate Boot Lock Bits for a Flexible Protection) Separate Fuse to Select Reset Vector Optimized Page(1) Size Code Efficient Algorithm Efficient Read-Modify-Write Support 1. A page is a section in the Flash consisting of several bytes (see "Page Size" on page 211) used during programming. The page organization does not affect normal operation.
Note:
29.2
Overview
The Boot Loader Support provides a real Read-While-Write Self-Programming mechanism for downloading and uploading program code by the MCU itself. This feature allows flexible application software updates controlled by the MCU using a Flash-resident Boot Loader program. The Boot Loader program can use any available data interface and associated protocol to read code and write (program) that code into the Flash memory, or read the code from the program memory. The program code within the Boot Loader section has the capability to write into the entire Flash, including the Boot Loader memory. The Boot Loader can thus even modify itself, and it can also erase itself from the code if the feature is not needed anymore. The size of the Boot Loader memory is configurable with fuses and the Boot Loader has two separate sets of Boot Lock bits which can be set independently. This gives the user a unique flexibility to select different levels of protection.
29.3
Application and Boot Loader Flash Sections
The Flash memory is organized in two main sections, the Application section and the Boot Loader section. The size of the different sections is configured by the BOOTSZ Fuses as shown in Table 29-5 on page 204 and Figure 29-2. These two sections can have different level of protection since they have different sets of Lock bits.
29.3.1
Application Section The Application section is the section of the Flash that is used for storing the application code. The protection level for the Application section can be selected by the application Boot Lock bits (Boot Lock bits 0), see Table 30-2 on page 208. The Application section can never store any Boot Loader code since the SPM instruction is disabled when executed from the Application section. BLS - Boot Loader Section While the Application section is used for storing the application code, the The Boot Loader software must be located in the BLS since the SPM instruction can initiate a programming when executing from the BLS only. The SPM instruction can access the entire Flash, including the BLS itself. The protection level for the Boot Loader section can be selected by the Boot Loader Lock bits (Boot Lock bits 1), see Table 30-2 on page 208.
29.3.2
191
8042A-AVR-07/09
ATmega16HVB/32HVB
29.4
Read-While-Write and No Read-While-Write Flash Sections
Whether the CPU supports Read-While-Write or if the CPU is halted during a Boot Loader software update is dependent on which address that is being programmed. In addition to the two sections that are configurable by the BOOTSZ Fuses as described above, the Flash is also divided into two fixed sections, the Read-While-Write (RWW) section and the No Read-WhileWrite (NRWW) section. The limit between the RWW- and NRWW sections is given in Table 296 on page 204 and Figure 29-2 on page 194. The main difference between the two sections is: * When erasing or writing a page located inside the RWW section, the NRWW section can be read during the operation. * When erasing or writing a page located inside the NRWW section, the CPU is halted during the entire operation. Note that the user software can never read any code that is located inside the RWW section during a Boot Loader software operation. The syntax "Read-While-Write section" refers to which section that is being programmed (erased or written), not which section that actually is being read during a Boot Loader software update.
29.4.1
RWW - Read-While-Write Section If a Boot Loader software update is programming a page inside the RWW section, it is possible to read code from the Flash, but only code that is located in the NRWW section. During an ongoing programming, the software must ensure that the RWW section never is being read. If the user software is trying to read code that is located inside the RWW section (i.e., by a call/jmp/lpm or an interrupt) during programming, the software might end up in an unknown state. To avoid this, the interrupts should either be disabled or moved to the Boot Loader section. The Boot Loader section is always located in the NRWW section. The RWW Section Busy bit (RWWSB) in the Store Program Memory Control and Status Register (SPMCSR) will be read as logical one as long as the RWW section is blocked for reading. After a programming is completed, the RWWSB must be cleared by software before reading code located in the RWW section. See "SPMCSR - Store Program Memory Control and Status Register" on page 206 for details on how to clear RWWSB. NRWW - No Read-While-Write Section The code located in the NRWW section can be read when the Boot Loader software is updating a page in the RWW section. When the Boot Loader code updates the NRWW section, the CPU is halted during the entire Page Erase or Page Write operation. Table 29-1. Read-While-Write Features
Which Section Can be Read During Programming? NRWW Section None CPU Halted? No Yes Read-While-Write Supported? Yes No
29.4.2
Which Section does the Z-pointer Address During the Programming? RWW Section NRWW Section
192
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 29-1. Read-While-Write vs. No Read-While-Write
Read-While-Write (RWW) Section
Z-pointer Addresses RWW Section
Z-pointer Addresses NRWW Section
No Read-While-Write (NRWW) Section
CPU is Halted During the Operation Code Located in NRWW Section Can be Read During the Operation
193
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 29-2. Memory Sections
Program Memory BOOTSZ = '11' 0x0000
Read-While-Write Section Read-While-Write Section
Program Memory BOOTSZ = '10' 0x0000
Application Flash Section
Application Flash Section
No Read-While-Write Section
End RWW Start NRWW Application Flash Section
No Read-While-Write Section
End RWW Start NRWW Application Flash Section End Application Start Boot Loader Boot Loader Flash Section Flashend Program Memory BOOTSZ = '00'
Boot Loader Flash Section
End Application Start Boot Loader Flashend
Program Memory BOOTSZ = '01' 0x0000
Read-While-Write Section Read-While-Write Section
0x0000
Application Flash Section
Application Flash Section
No Read-While-Write Section
End RWW Start NRWW Application Flash Section End Application Start Boot Loader Boot Loader Flash Section Flashend
No Read-While-Write Section
End RWW, End Application Start NRWW, Start Boot Loader
Boot Loader Flash Section
Flashend
Note:
1. The parameters in the figure above are given in Table 29-5 on page 204.
29.5
Boot Loader Lock Bits
If no Boot Loader capability is needed, the entire Flash is available for application code. The Boot Loader has two separate sets of Boot Lock bits which can be set independently. This gives the user a unique flexibility to select different levels of protection. The user can select: * To protect the entire Flash from a software update by the MCU. * To protect only the Boot Loader Flash section from a software update by the MCU. * To protect only the Application Flash section from a software update by the MCU. * Allow software update in the entire Flash. See Table 30-2 on page 208 for further details. The Boot Lock bits can be set in software and in Serial or Parallel Programming mode, but they can be cleared by a Chip Erase command only. The general Write Lock (Lock Bit mode 2) does not control the programming of the Flash memory by SPM instruction. Similarly, the general Read/Write Lock (Lock Bit mode 1) does not control reading nor writing by LPM/SPM, if it is attempted. 194
8042A-AVR-07/09
ATmega16HVB/32HVB
29.6 Entering the Boot Loader Program
Entering the Boot Loader takes place by a jump or call from the application program. This may be initiated by a trigger such as a command received via the TWI interface. Alternatively, the Boot Reset Fuse can be programmed so that the Reset Vector is pointing to the Boot Flash start address after a reset. In this case, the Boot Loader is started after a reset. After the application code is loaded, the program can start executing the application code. Note that the fuses cannot be changed by the MCU itself. This means that once the Boot Reset Fuse is programmed, the Reset Vector will always point to the Boot Loader Reset and the fuse can only be changed through the serial or parallel programming interface. Table 29-2.
BOOTRST 1 0 Note:
Boot Reset Fuse(1)
Reset Address Reset Vector = Application Reset (address 0x0000) Reset Vector = Boot Loader Reset (see Table 29-5 on page 204)
1. "1" means unprogrammed, "0" means programmed
195
8042A-AVR-07/09
ATmega16HVB/32HVB
29.7
Addressing the Flash During Self-Programming
The Z-pointer is used to address the SPM commands.
Bit ZH (R31) ZL (R30) 15 Z15 Z7 7 14 Z14 Z6 6 13 Z13 Z5 5 12 Z12 Z4 4 11 Z11 Z3 3 10 Z10 Z2 2 9 Z9 Z1 1 8 Z8 Z0 0
Since the Flash is organized in pages (see "Fuse Bits" on page 209), the Program Counter can be treated as having two different sections. One section, consisting of the least significant bits, is addressing the words within a page, while the most significant bits are addressing the pages. This is shown in Figure 29-3. Note that the Page Erase and Page Write operations are addressed independently. Therefore it is of major importance that the Boot Loader software addresses the same page in both the Page Erase and Page Write operation. Once a programming operation is initiated, the address is latched and the Z-pointer can be used for other operations. The only SPM operation that does not use the Z-pointer is Setting the Boot Loader Lock bits. The content of the Z-pointer is ignored and will have no effect on the operation. The LPM instruction does also use the Z-pointer to store the address. Since this instruction addresses the Flash byte-by-byte, also the LSB (bit Z0) of the Z-pointer is used. Figure 29-3. Addressing the Flash During SPM(1)
BIT Z - REGISTER PCMSB PROGRAM COUNTER
PCPAGE
15
ZPCMSB
ZPAGEMSB
10 0
PAGEMSB
PCWORD
PAGE ADDRESS WITHIN THE FLASH PROGRAM MEMORY
PAGE
WORD ADDRESS WITHIN A PAGE
PAGE INSTRUCTION WORD PCWORD[PAGEMSB:0]: 00 01 02
PAGEEND
Note:
1. The different variables used in Figure 29-3 are listed in Table 29-7 on page 204 and Table 2910 on page 205.
196
8042A-AVR-07/09
ATmega16HVB/32HVB
29.8 Self-Programming the Flash
The program memory is updated in a page by page fashion. Before programming a page with the data stored in the temporary page buffer, the page must be erased. The temporary page buffer is filled one word at a time using SPM and the buffer can be filled either before the Page Erase command or between a Page Erase and a Page Write operation: Alternative 1, fill the buffer before a Page Erase * Fill temporary page buffer * Perform a Page Erase * Perform a Page Write Alternative 2, fill the buffer after Page Erase * Perform a Page Erase * Fill temporary page buffer * Perform a Page Write If only a part of the page needs to be changed, the rest of the page must be stored (for example in the temporary page buffer) before the erase, and then be rewritten. When using alternative 1, the Boot Loader provides an effective Read-Modify-Write feature which allows the user software to first read the page, do the necessary changes, and then write back the modified data. If alternative 2 is used, it is not possible to read the old data while loading since the page is already erased. The temporary page buffer can be accessed in a random sequence. It is essential that the page address used in both the Page Erase and Page Write operation is addressing the same page. See "Simple Assembly Code Example for a Boot Loader" on page 202 for an assembly code example. 29.8.1 Performing Page Erase by SPM To execute Page Erase, set up the address in the Z-pointer, write "X0000011" to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The data in R1 and R0 is ignored. The page address must be written to PCPAGE in the Z-register. Other bits in the Z-pointer will be ignored during this operation. * Page Erase to the RWW section: The NRWW section can be read during the Page Erase. * Page Erase to the NRWW section: The CPU is halted during the operation. 29.8.2 Filling the Temporary Buffer (Page Loading) To write an instruction word, set up the address in the Z-pointer and data in R1:R0, write "X0000001" to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The content of PCWORD in the Z-register is used to address the data in the temporary buffer. The temporary buffer will auto-erase after a Page Write operation or by writing the RWWSRE bit in SPMCSR. It is also erased after a system reset. Note that it is not possible to write more than one time to each address without erasing the temporary buffer.
197
8042A-AVR-07/09
ATmega16HVB/32HVB
29.8.3 Performing a Page Write To execute Page Write, set up the address in the Z-pointer, write "X0000101" to SPMCSR and execute SPM within four clock cycles after writing SPMCSR. The data in R1 and R0 is ignored. The page address must be written to PCPAGE. Other bits in the Z-pointer will be ignored during this operation. * Page Write to the RWW section: The NRWW section can be read during the Page Write. * Page Write to the NRWW section: The CPU is halted during the operation. 29.8.4 Using the SPM Interrupt If the SPM interrupt is enabled, the SPM interrupt will generate a constant interrupt when the SPMEN bit in SPMCSR is cleared. This means that the interrupt can be used instead of polling the SPMCSR Register in software. When using the SPM interrupt, the Interrupt Vectors should be moved to the BLS section to avoid that an interrupt is accessing the RWW section when it is blocked for reading. How to move the interrupts is described in "Interrupts" on page 52. Consideration While Updating BLS Special care must be taken if the user allows the Boot Loader section to be updated by leaving Boot Lock bit11 unprogrammed. An accidental write to the Boot Loader itself can corrupt the entire Boot Loader, and further software updates might be impossible. If it is not necessary to change the Boot Loader software itself, it is recommended to program the Boot Lock bit11 to protect the Boot Loader software from any internal software changes. Prevent Reading the RWW Section During Self-Programming During Self-Programming (either Page Erase or Page Write), the RWW section is always blocked for reading. The user software itself must prevent that this section is addressed during the self programming operation. The RWWSB in the SPMCSR will be set as long as the RWW section is busy. During Self-Programming the Interrupt Vector table should be moved to the BLS as described in "Interrupts" on page 52, or the interrupts must be disabled. Before addressing the RWW section after the programming is completed, the user software must clear the RWWSB by writing the RWWSRE. See "Simple Assembly Code Example for a Boot Loader" on page 202 for an example. Setting the Lock Bits by SPM To set the Lock bits, write the desired data to R0, write "X0001001" to SPMCSR and execute SPM within four clock cycles after writing SPMCSR.
Bit R0 7 1 6 1 5 BLB12 4 BLB11 3 BLB02 2 BLB01 1 LB2 0 LB1
29.8.5
29.8.6
29.8.7
See Table 30-2 on page 208 for how the different settings of the Lock bits affect the Flash access. If bits 5:0 in R0 are cleared (zero), the corresponding Lock bit will be programmed if an SPM instruction is executed within four cycles after LBSET and SPMEN are set in SPMCSR. The Zpointer is don't care during this operation, but for future compatibility it is recommended to load the Z-pointer with 0x0001 (same as used for reading the lOck bits). For future compatibility it is also recommended to set bits 7 and 6 in R0 to "1" when writing the Lock bits. When programming the Lock bits the entire Flash can be read during the operation.
198
8042A-AVR-07/09
ATmega16HVB/32HVB
29.8.8 Reading the Fuse and Lock Bits from Software It is possible to read both the Fuse and Lock bits from software. To read the Lock bits, load the Z-pointer with 0x0001 and set the LBSET and SPMEN bits in SPMCSR. When an LPM instruction is executed within three CPU cycles after the LBSET and SPMEN bits are set in SPMCSR, the value of the Lock bits will be loaded in the destination register. The LBSET and SPMEN bits will auto-clear upon completion of reading the Lock bits. When LBSET and SPMEN are cleared, LPM will work as described in the "AVR Instruction Set" description.
Bit Rd 7 - 6 - 5 BLB12 4 BLB11 3 BLB02 2 BLB01 1 LB2 0 LB1
The algorithm for reading the Fuse Low byte is similar to the one described above for reading the Lock bits. To read the Fuse Low byte, load the Z-pointer with 0x0000 and set the LBSET and SPMEN bits in SPMCSR. When an LPM instruction is executed within three cycles after the LBSET and SPMEN bits are set in the SPMCSR, the value of the Fuse Low byte (FLB) will be loaded in the destination register as shown below. Refer to Table 30-4 on page 210 for a detailed description and mapping of the Fuse Low byte.
Bit Rd 7 FLB7 6 FLB6 5 FLB5 4 FLB4 3 FLB3 2 FLB2 1 FLB1 0 FLB0
Similarly, when reading the Fuse High byte, load 0x0003 in the Z-pointer. When an LPM instruction is executed within three cycles after the LBSET and SPMEN bits are set in the SPMCSR, the value of the Fuse High byte (FHB) will be loaded in the destination register as shown below. Refer to Table 30-3 on page 209 for detailed description and mapping of the Fuse High byte.
Bit Rd 7 FHB7 6 FHB6 5 FHB5 4 FHB4 3 FHB3 2 FHB2 1 FHB1 0 FHB0
Fuse and Lock bits that are programmed, will be read as zero. Fuse and Lock bits that are unprogrammed, will be read as one. 29.8.9 Reading the Signature Row from Software To read the Signature Row from software, load the Z-pointer with the signature byte address given in Table 29-3 and set the SIGRD and SPMEN bits in SPMCSR. When an LPM instruction is executed within three CPU cycles after the SIGRD and SPMEN bits are set in SPMCSR, the signature byte value will be loaded in the destination register. The SIGRD and SPMEN bits will auto-clear 6 cycles after writing to SPMCSR, which is locked for further writing during these cycles. When SIGRD and SPMEN are cleared, LPM will work as described in the Instruction set Manual
Table 29-3.
Signature Row Addressing.
Z-Pointer Address 00H 02H 04H 01H
(2)
Signature Byte Description Device ID 0, Manufacture ID Device ID 1, Flash Size Device ID 2, Device FOSCCAL
(1)
FOSC SEGMENT Reserved
03H 05H
199
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 29-3. Signature Row Addressing. (Continued)
Z-Pointer Address 06H
(3)
Signature Byte Description SLOW RC Period L SLOW RC Period H
07H 08H 09H 0AH
SLOW RC Temp Prediction L SLOW RC Temp Prediction H(4) ULP RC FRQ(5) SLOW RC FRQ
(6)
0BH OCH ODH OEH
ULP RC Temp Prediction Coefficient L ULP RC Temp Prediction Coefficient H(7) ULP RC Period L ULP RC Period H
(8)
OFH 10H 11H 12H:17H 18H
BGCRR Calibration Byte BGCCR Calibration Byte Reserved VPTAT CAL L VPTAT CAL H
(9)
19H 1AH 1BH 1CH
(10)
V-ADC Cell1 Gain Calibration Word L V-ADC Cell1 Gain Calibration Word H(10) V-ADC Cell2 Gain Calibration Word L V-ADC Cell2 Gain Calibration Word H V-ADC Cell3 Gain Calibration Word L V-ADC Cell3 Gain Calibration Word H V-ADC Cell4 Gain Calibration Word L V-ADC Cell4 Gain Calibration Word H V-ADC Cell1 Offset(11) V-ADC Cell2 Offset(11) V-ADC Cell3 Offset V-ADC Cell4 Offset
(11) (11) (10) (10)
1DH 1EH 1FH 20H 21H 22H 23H 24H 25H 26H 27H 28H
V-ADC0 Gain Calibration Word L V-ADC0 Gain Calibration Word H(12) V-ADC1 Gain Calibration Word L V-ADC1 Gain Calibration Word H V-ADC ADC0 Offset(14) V-ADC ADC1 Offset Reserved THOT
(15) (14) (13)
29H 2AH 2BH 2CH:2FH 30H
Notes:
1. Default FOSCCAL value after reset.
200
8042A-AVR-07/09
ATmega16HVB/32HVB
2. FOSCCAL setting used to smooth the transition from one segment to the next when calibrating the Fast RC oscillator. 3. 8 prescaled Slow RC periods in s using the Oscillator Sampling Interface (@THOTC). 4. Slow RC oscillator frequency temperature drift prediction value. 5. ULP RC oscillator frequency in kHz (@ THOTC). 6. Slow RC oscillator frequency in kHz (@THOTC). 7. ULP RC oscillator frequency temperature drift prediction value. 8. 8 prescaled ULP RC periods in s using the Oscillator Sampling Interface (@THOTC). 9. Calibration word used to calculate the absolute temperature in Kelvin from a VTEMP conversion. 10. Calibration word used to compensate for gain error in V-ADC Cells. 11. Calibration byte used to compensate for offset in V-ADC Cells. 12. Calibration word used to compensate for gain error in ADC0. 13. Calibration word used to compensate for gain error in ADC1. 14. Calibration byte used to compensate for offset in ADC0 and ADC1. 15. Hot temperature used for factory calibration in C.
All other addresses are reserved for future use. 29.8.10 SPMCSR writing restrictions Writing any other combination than "100001", "010001", "001001", "000101", "000011" or "000001" in the lower six bits will have no effect. SPMCSR is locked for writing under the following conditions: * One or more of the bits 5:0 in SPMCSR is set to 1 * During EEPROM write (status bit EEWE in EECR is set)
SPMCSR will be cleared at the following events: * on completion of successful execution the following instructions: - LPM with LBSET and SPMEN set - SPM with LBSET and SPMEN set - SPM with PGERS and SPMEN set - SPM with PGWRT and SPMEN set - SPM with SPMEN set * six cycles after writing SPMCSR if any other or no LPM/SPM is executed 29.8.11 Programming Time for Flash when Using SPM The Fast RC Oscillator is used to time Flash accesses. Table 29-4 shows the typical programming time for Flash accesses from the CPU. Table 29-4. SPM Programming Time(1)
Symbol Flash write (Page Erase, Page Write, and write Lock bits by SPM) Note: Min Programming Time 3.7 ms Max Programming Time 4.5 ms
1. Minimum and maximum programming time is per individual operation.
201
8042A-AVR-07/09
ATmega16HVB/32HVB
29.8.12 Simple Assembly Code Example for a Boot Loader
;-the routine writes one page of data from RAM to Flash ; the first data location in RAM is pointed to by the Y pointer ; the first data location in Flash is pointed to by the Z-pointer ;-error handling is not included ;-the routine must be placed inside the Boot space ; (at least the Do_spm sub routine). Only code inside NRWW section ; can be read during Self-Programming (Page Erase and Page Write). ;-registers used: r0, r1, temp1 (r16), temp2 (r17), looplo (r24), ; loophi (r25), spmcrval (r20) ; storing and restoring of registers is not included in the routine ; register usage can be optimized at the expense of code size ;-It is assumed that either the interrupt table is moved to the ; Boot loader section or that the interrupts are disabled. .equ PAGESIZEB = PAGESIZE*2 ;PAGESIZEB is page size in BYTES, not words .org SMALLBOOTSTART Write_page: ; Page Erase ldi spmcrval, (1<202
8042A-AVR-07/09
ATmega16HVB/32HVB
sbiw loophi:looplo, 1 ;use subi for PAGESIZEB<=256 brne Rdloop ; return to RWW section ; verify that RWW section is safe to read Return: in temp1, SPMCSR sbrs temp1, RWWSB ; If RWWSB is set, the RWW section is not ready yet ret ; re-enable the RWW section ldi spmcrval, (1<203
8042A-AVR-07/09
ATmega16HVB/32HVB
29.8.13 ATmega16HVB Boot Loader Parameters In Table 29-5 through Table 29-7, the parameters used in the description of the Self-Programming are given Table 29-5. Boot Size Configuration(1)
End Application Section 0x1EFF 0x1DFF 0x1BFF 0x17FF Boot Reset Address (Start Boot Loader Section) 0x1F00 0x1E00 0x1C00 0x1800 Application Flash Section Boot Loader Flash Section 0x1F00 - 0x1FFF 0x1E00 - 0x1FFF 0x1C00 - 0x1FFF 0x1800 - 0x1FFF Pages 96 32 Description Most significant bit in the Program Counter. (The Program Counter is 13 bits PC[12:0]) Most significant bit which is used to address the words within one page (64 words in a page requires six bits PC [5:0]). Z13 Bit in Z-register that is mapped to PCMSB. Because Z0 is not used, the ZPCMSB equals PCMSB + 1. Bit in Z-register that is mapped to PCMSB. Because Z0 is not used, the ZPAGEMSB equals PAGEMSB + 1. Program Counter page address: Page select, for Page Erase and Page Write Program Counter word address: Word select, for filling temporary buffer (must be zero during Page Write operation)
BOOTSZ1
BOOTSZ0
Boot Size 256 words 512 words 1024 words 2048 words
1 1 0 0 Note:
1 0 1 0
Pages 4 8 16 32
0x0000 - 0x1EFF 0x0000 - 0x1DFF 0x0000 - 0x1BFF 0x0000 - 0x17FF
1. The different BOOTSZ Fuse configurations are shown in Figure 29-2
Table 29-6.
Section
Read-While-Write Limit(1)
Address 0x0000 - 0x17FF 0x1800 - 0x1FFF
Read-While-Write section (RWW) No Read-While-Write section (NRWW) Note:
1. For details about these two section, see "NRWW - No Read-While-Write Section" on page 192 and "RWW - Read-While-Write Section" on page 192.
Table 29-7.
Explanation of different variables used in Figure 29-3 on page 196 and the mapping to the Z-pointer(1)
Corresponding Z-value 12
Variable PCMSB
PAGEMSB
5
ZPCMSB
ZPAGEMSB
Z6
PCPAGE
PC[12:6]
Z12:Z7
PCWORD
PC[5:0]
Z6:Z1
204
8042A-AVR-07/09
ATmega16HVB/32HVB
Note: 1. Z0: should be zero for all SPM commands, byte select for the LPM instruction. See "Addressing the Flash During Self-Programming" on page 196 for details about the use of Z-pointer during Self-Programming.
29.8.14
ATmega32HVB Boot Loader Parameters In Table 29-8 through Table 29-10, the parameters used in the description of the Self-Programming are given Table 29-8. Boot Size Configuration(1)
End Application Section 0x3EFF 0x3DFF 0x3BFF 0x37FF Boot Reset Address (Start Boot Loader Section) 0x3F00 0x3E00 0x3C00 0x3800 Application Flash Section Boot Loader Flash Section 0x3F00 - 0x3FFF 0x3E00 - 0x3FFF 0x3C00 - 0x3FFF 0x3800 - 0x3FFF Pages 224 32 Description Most significant bit in the Program Counter. (The Program Counter is 14 bits PC[13:0]) Most significant bit which is used to address the words within one page (64 words in a page requires six bits PC [5:0]). Z14 Bit in Z-register that is mapped to PCMSB. Because Z0 is not used, the ZPCMSB equals PCMSB + 1. Bit in Z-register that is mapped to PCMSB. Because Z0 is not used, the ZPAGEMSB equals PAGEMSB + 1. Program Counter page address: Page select, for Page Erase and Page Write Program Counter word address: Word select, for filling temporary buffer (must be zero during Page Write operation)
BOOTSZ1
BOOTSZ0
Boot Size 256 words 512 words 1024 words 2048 words
1 1 0 0 Note:
1 0 1 0
Pages 4 8 16 32
0x0000 - 0x3EFF 0x0000 - 0x3DFF 0x0000 - 0x3BFF 0x0000 - 0x37FF
1. The different BOOTSZ Fuse configurations are shown in Figure 29-2
Table 29-9.
Section
Read-While-Write Limit(1)
Address 0x0000 - 0x37FF 0x3800 - 0x3FFF
Read-While-Write section (RWW) No Read-While-Write section (NRWW)
For details about these two section, see "NRWW - No Read-While-Write Section" on page 192 and "RWW - Read-While-Write Section" on page 192.
Table 29-10. Explanation of different variables used in Figure 29-3 on page 196 and the mapping to the Z-pointer(1)
Variable PCMSB 13 Corresponding Z-value
PAGEMSB
5
ZPCMSB
ZPAGEMSB
Z6
PCPAGE
PC[13:6]
Z13:Z7
PCWORD
PC[5:0]
Z6:Z1
205
8042A-AVR-07/09
ATmega16HVB/32HVB
Note: 1. Z0: should be zero for all SPM commands, byte select for the LPM instruction. See "Addressing the Flash During Self-Programming" on page 196 for details about the use of Z-pointer during Self-Programming.
29.9
29.9.1
Register Description
SPMCSR - Store Program Memory Control and Status Register The Store Program Memory Control and Status Register contains the control bits needed to control the Boot Loader operations.
Bit 0x37 (0x57) Read/Write Initial Value 7
SPMIE
6
RWWSB
5
SIGRD
4
RWWSRE
3
LBSET
2
PGWRT
1
PGERS
0
SPMEN SPMCSR
R/W 0
R 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
R/W 0
* Bit 7 - SPMIE: SPM Interrupt Enable When the SPMIE bit is written to one, and the I-bit in the Status Register is set (one), the SPM ready interrupt will be enabled. The SPM ready Interrupt will be executed as long as the SPMEN bit in the SPMCSR Register is cleared. * Bit 6 - RWWSB: Read-While-Write Section Busy When a Self-Programming (Page Erase or Page Write) operation to the RWW section is initiated, the RWWSB will be set (one) by hardware. When the RWWSB bit is set, the RWW section cannot be accessed. The RWWSB bit will be cleared if the RWWSRE bit is written to one after a Self-Programming operation is completed. Alternatively the RWWSB bit will automatically be cleared if a page load operation is initiated. * Bit 5 - SIGRD: Signature Row Read If this bit is written to one at the same time as SPMEN, the next LPM instruction within three clock cycles will read a byte from the signature row into the destination register. See"Reading the Signature Row from Software" on page 199 for details. An SPM instruction within four cycles after SIGRD and SPMEN are set will have no effect. This operation is reserved for future use and should not be used. * Bit 4 - RWWSRE: Read-While-Write Section Read Enable When programming (Page Erase or Page Write) to the RWW section, the RWW section is blocked for reading (the RWWSB will be set by hardware). To re-enable the RWW section, the user software must wait until the programming is completed (SPMEN will be cleared). Then, if the RWWSRE bit is written to one at the same time as SPMEN, the next SPM instruction within four clock cycles re-enables the RWW section. The RWW section cannot be re-enabled while the Flash is busy with a Page Erase or a Page Write (SPMEN is set). If the RWWSRE bit is written while the Flash is being loaded, the Flash load operation will abort and the data loaded will be lost. * Bit 3 - LBSET: Lock Bit Set If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock cycles sets Lock bits, according to the data in R0. The data in R1 and the address in the Zpointer are ignored. The LBSET bit will automatically be cleared upon completion of the Lock bit set, or after six cycles if no SPM instruction is executed within four clock cycles.
206
8042A-AVR-07/09
ATmega16HVB/32HVB
An LPM instruction within three cycles after LBSET and SPMEN are set in the SPMCSR Register, will read either the Lock bits or the Fuse bits (depending on Z0 in the Z-pointer) into the destination register. See "Reading the Fuse and Lock Bits" on page 224 for details.
* Bit 2 - PGWRT: Page Write If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock cycles executes Page Write, with the data stored in the temporary buffer. The page address is taken from the high part of the Z-pointer. The data in R1 and R0 are ignored. The PGWRT bit will auto-clear upon completion of a Page Write, or after six cycles if no SPM instruction is executed within four clock cycles. The CPU is halted during the entire Page Write operation if the NRWW section is addressed. * Bit 1 - PGERS: Page Erase If this bit is written to one at the same time as SPMEN, the next SPM instruction within four clock cycles executes Page Erase. The page address is taken from the high part of the Z-pointer. The data in R1 and R0 are ignored. The PGERS bit will auto-clear upon completion of a Page Erase, or after six cycles if no SPM instruction is executed within four clock cycles. The CPU is halted during the entire Page Write operation if the NRWW section is addressed. * Bit 0 - SPMEN: Store Program Memory Enable This bit enables the SPM instruction for the next four clock cycles. If written to one together with either RWWSRE, LBSET, PGWRT' or PGERS, the following SPM instruction will have a special meaning, see description above. If only SPMEN is written, the following SPM instruction will store the value in R1:R0 in the temporary page buffer addressed by the Z-pointer. The LSB of the Z-pointer is ignored. The SPMEN bit will auto-clear upon completion of an SPM instruction, or after six cycles if no SPM instruction is executed within four clock cycles. During Page Erase and Page Write, the SPMEN bit remains high until the operation is completed.
207
8042A-AVR-07/09
ATmega16HVB/32HVB
30. Memory Programming
30.1 Program And Data Memory Lock Bits
The ATmega16HVB/32HVB provides six Lock bits which can be left unprogrammed ("1") or can be programmed ("0") to obtain the additional features listed in Table 30-2. The Lock bits can only be erased to "1" with the Chip Erase command. Table 30-1.
Lock Bit Byte
Lock Bit Byte(1)
Bit No 7 6 Description - - Boot Lock bit Boot Lock bit Boot Lock bit Boot Lock bit Lock bit Lock bit Default Value 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed) 1 (unprogrammed)
BLB12 BLB11 BLB02 BLB01 LB2 LB1 Note:
5 4 3 2 1 0
1. "1" means unprogrammed, "0" means programmed
Table 30-2.
Lock Bit Protection Modes(1)(2)
Protection Type LB1 1 0 No memory lock features enabled. Further programming of the Flash and EEPROM is disabled in Parallel and Serial Programming mode. The Fuse bits are locked in both Serial and Parallel Programming mode.(1) Further programming and verification of the Flash and EEPROM is disabled in Parallel and Serial Programming mode. The Boot Lock bits and Fuse bits are locked in both Serial and Parallel Programming mode.(1)
Memory Lock Bits LB Mode 1 2 LB2 1 1
3
0
0
BLB0 Mode 1 2
BLB02 1 1
BLB01 1 0 No restrictions for SPM or LPM accessing the Application section. SPM is not allowed to write to the Application section. SPM is not allowed to write to the Application section, and LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section. LPM executing from the Boot Loader section is not allowed to read from the Application section. If Interrupt Vectors are placed in the Boot Loader section, interrupts are disabled while executing from the Application section.
3
0
0
4
0
1
208
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 30-2. Lock Bit Protection Modes(1)(2) (Continued)
Protection Type
Memory Lock Bits BLB1 Mode 1 2 BLB12 1 1 BLB11 1 0
No restrictions for SPM or LPM accessing the Boot Loader section. SPM is not allowed to write to the Boot Loader section. SPM is not allowed to write to the Boot Loader section, and LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section. LPM executing from the Application section is not allowed to read from the Boot Loader section. If Interrupt Vectors are placed in the Application section, interrupts are disabled while executing from the Boot Loader section.
3
0
0
4
0
1
Notes:
1. Program the Fuse bits and Boot Lock bits before programming the LB1 and LB2. 2. "1" means unprogrammed, "0" means programmed
30.2
Fuse Bits
The ATmega16HVB/32HVB has two Fuse bytes. Table 30-4 and Table 30-3 describe briefly the functionality of all the fuses and how they are mapped into the Fuse byte. Note that the fuses are read as logical zero, "0", if they are programmed.
30.2.1
High Byte
Table 30-3.
Bit No 7:5 4 3 2 1 0 Notes:
Fuse High Byte
Fuse High Byte - DUVRDINIT(1) DWEN BOOTSZ1 BOOTSZ0 BOOTRST Reset Value of DUVRDRegister Enable debugWire Select Boot Size Select Boot Size Select Reset Vector 0 (programmed) 1 (unprogrammed) 0 (programmed)(2) 0 (programmed)(2) 1 (unprogrammed) Description Default Value
1. The default DUVRDINIT should not be changed. DUVRDINIT= "1" is reserved for future use. 2. The default value of BOOTSZ1:0 results in maximum Boot Size.
209
8042A-AVR-07/09
ATmega16HVB/32HVB
30.2.2 Low Byte
Table 30-4.
Bit No 7 6 5 4 3 2 1 0 Notes:
Fuse Low Byte
Description Watchdog Timer always on EEPROM memory is preserved through the Chip Erase Enable Serial Programmable Data Downloading Select start-up time Select start-up time Select start-up time Oscillator Select Oscillator Select Default Value 1 (unprogrammed)(1) 1 (unprogrammed, EEPROM not preserved) 0 (programmed, SPI programming enabled) 1 (unprogrammed)(2) 1 (unprogrammed)(2) 1 (unprogrammed)(2) 1(unprogrammed)(3) 0(programmed)(3)
Fuse Low Byte WDTON EESAVE SPIEN SUT2 SUT1 SUT0 OSCSEL1 OSCSEL0
1. The Watchdog is enabled/disabling by writing to the Watchdog Timer Control and Status Register (WDTCSR). But as a fail-safe, the WDTON fuse can be used to force the Watchdog to run in System Reset mode. 2. The SUTx fuse bits are used to configure the startup time from sleep or reset. By default the longest startup time is selected. 3. The default OSCSEL1:0 setting should not be changed. OSCSEL1:0="00" is reserved for test purpose. Other values are reserved for future use.
The status of the Fuse bits is not affected by Chip Erase. Note that the Fuse bits are locked if Lock bit1 (LB1) is programmed. Program the Fuse bits before programming the Lock bits. 30.2.3 Latching of Fuses The fuse values are latched when the device enters programming mode and changes of the fuse values will have no effect until the part leaves Programming mode. This does not apply to the EESAVE Fuse which will take effect once it is programmed. The fuses are also latched on Power-up in Normal mode.
30.3
Signature Bytes
All Atmel microcontrollers have a three-byte signature code which identifies the device. This code can be read in both Programming mode, also when the device is locked. The three bytes reside in a separate address space. The signature bytes of ATmega16HVB/32HVB is given in Table 30-5. Table 30-5. Device ID
Signature Bytes Address Part ATmega16HVB ATmega32HVB 0x000 0x1E 0x1E 0x001 0x94 0x95 0x002 0x0D 0x10
210
8042A-AVR-07/09
ATmega16HVB/32HVB
30.4 Calibration Bytes
The ATmega16HVB/32HVB has calibration bytes for the RC Oscillators, internal voltage reference, internal temperature reference and each differential cell voltage input. These bytes reside in the signature address space. See "Reading the Signature Row from Software" on page 199 for details.
30.5
Page Size
Table 30-6. No. of Words in a Page and No. of Pages in the Flash, ATmega16HVB
Page Size 64 words PCWORD PC[5:0] No. of Pages 128 PCPAGE PC[12:6] PCMSB 12
Flash Size 8K words (16K bytes)
Table 30-7.
No. of Words in a Page and No. of Pages in the Flash, ATmega32HVB
Page Size 64 words PCWORD PC[5:0] No. of Pages 256 PCPAGE PC[13:6] PCMSB 13
Flash Size 16K words (32K bytes)
Table 30-8.
No. of Words in a Page and No. of Pages in the EEPROM, ATmega16HVB
Page Size 4 bytes PCWORD EEA[1:0] No. of Pages 128 PCPAGE EEA[8:2] EEAMSB 8
EEPROM Size 512 bytes
Table 30-9.
No. of Words in a Page and No. of Pages in the EEPROM, ATmega32HVB
Page Size 4 bytes PCWORD EEA[1:0] No. of Pages 256 PCPAGE EEA[9:2] EEAMSB 9
EEPROM Size 1K bytes
30.6
Serial Programming
Both the Flash and EEPROM memory arrays can be programmed using the serial SPI bus while RESET is pulled to GND. The serial interface consists of pins SCK, MOSI (input) and MISO (output). After RESET is set low, the Programming Enable instruction needs to be executed first before program/erase operations can be executed. NOTE, in Table 30-10 on page 212, the pin mapping for SPI programming is listed. Not all parts use the SPI pins dedicated for the internal SPI interface.
211
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 30-1. Serial Programming and Verify.
+3.3 - 4.5V VCC MOSI MISO SCK
RESET
GND
Table 30-10. Pin Mapping Serial Programming
Symbol SCK MOSI MISO Pins PB5 PB6 PB7 I/O I I O Description Serial Clock Serial Data in Serial Data out
When programming the EEPROM, an auto-erase cycle is built into the self-timed programming operation (in the Serial mode ONLY) and there is no need to first execute the Chip Erase instruction. The Chip Erase operation turns the content of every memory location in both the Program and EEPROM arrays into 0xFF. Depending on OSCSEL Fuses, a valid clock must be present. The minimum low and high periods for the serial clock (SCK) input are defined as follows: Low: > 2.2 CPU clock cycles for fck < 12 MHz, 3 CPU clock cycles for fck >= 12 MHz High: > 2.2 CPU clock cycles for fck < 12 MHz, 3 CPU clock cycles for fck >= 12 MHz
30.6.1
Serial Programming Algorithm When writing serial data to the ATmega16HVB/32HVB, data is clocked on the rising edge of SCK. When reading data from the ATmega16HVB/32HVB, data is clocked on the falling edge of SCK. See "Serial Programming Characteristics" on page 237 for timing details. To program and verify the ATmega16HVB/32HVB in the Serial Programming mode, the following sequence is recommended (see four byte instruction formats in Table 30-12 on page 214): 1. Power-up sequence: Apply power between VCC and GND while RESET and SCK are set to "0". In some systems, the programmer can not guarantee that SCK is held low during power-up. In this
212
8042A-AVR-07/09
ATmega16HVB/32HVB
case, RESET must be given a positive pulse of at least two CPU clock cycles duration after SCK has been set to "0". 2. Wait for at least 20 ms and enable serial programming by sending the Programming Enable serial instruction to pin MOSI. 3. The serial programming instructions will not work if the communication is out of synchronization. When in sync. the second byte (0x53), will echo back when issuing the third byte of the Programming Enable instruction. Whether the echo is correct or not, all four bytes of the instruction must be transmitted. If the 0x53 did not echo back, give RESET a positive pulse and issue a new Programming Enable command. 4. The Flash is programmed one page at a time. The memory page is loaded one byte at a time by supplying the 5 LSB of the address and data together with the Load Program memory Page instruction. To ensure correct loading of the page, the data low byte must be loaded before data high byte is applied for a given address. The Program memory Page is stored by loading the Write Program memory Page instruction with the 6 MSB of the address. If polling (RDY/BSY) is not used, the user must wait at least tWD_FLASH before issuing the next page. (See Table 30-11.) Accessing the serial programming interface before the Flash write operation completes can result in incorrect programming. 5. A: The EEPROM array is programmed one byte at a time by supplying the address and data together with the appropriate Write instruction. An EEPROM memory location is first automatically erased before new data is written. If polling (RDY/BSY) is not used, the user must wait at least tWD_EEPROM before issuing the next byte. (See Table 30-11.) In a chip erased device, no 0xFFs in the data file(s) need to be programmed. B: The EEPROM array is programmed one page at a time. The Memory page is loaded one byte at a time by supplying the 2 LSB of the address and data together with the Load EEPROM Memory Page instruction. The EEPROM Memory Page is stored by loading the Write EEPROM Memory Page Instruction with the 6 MSB of the address. When using EEPROM page access only byte locations loaded with the Load EEPROM Memory Page instruction is altered. The remaining locations remain unchanged. If polling (RDY/BSY) is not used, the used must wait at least tWD_EEPROM before issuing the next page (See Table 30-8 on page 211). In a chip erased device, no 0xFF in the data file(s) need to be programmed. 6. Any memory location can be verified by using the Read instruction which returns the content at the selected address at serial output MISO. 7. At the end of the programming session, RESET can be set high to commence normal operation. 8. Power-off sequence (if needed): Set RESET to "1". Turn VCC power off. Table 30-11. Minimum Wait Delay Before Writing the Next Flash or EEPROM Location
Symbol tWD_FLASH tWD_EEPROM tWD_ERASE tWD_FUSE Minimum Wait Delay 4.5 ms 4.0 ms 4.0 ms 4.5 ms
213
8042A-AVR-07/09
ATmega16HVB/32HVB
30.6.2 Serial Programming Instruction set Table 30-12 on page 214 and Figure 30-2 on page 215 describes the Instruction set. Table 30-12. Serial Programming Instruction Set
Instruction Format Instruction/Operation Programming Enable Chip Erase (Program Memory/EEPROM) Poll RDY/BSY Load Instructions Load Extended Address byte(1) Load Program Memory Page, High byte Load Program Memory Page, Low byte Load EEPROM Memory Page (page access) Read Instructions Read Program Memory, High byte Read Program Memory, Low byte Read EEPROM Memory Read Lock bits Read Signature Byte Read Fuse bits Read Fuse High bits Read Extended Fuse Bits Read Calibration Byte Write Instructions(6) Write Program Memory Page Write EEPROM Memory Write EEPROM Memory Page (page access) Write Lock bits Write Fuse bits Write Fuse High bits Write Extended Fuse Bits Notes: 1. 2. 3. 4. 5. 6. 7. $4C $C0 $C2 $AC $AC $AC $AC adr MSB adr MSB adr MSB $E0 $A0 $A8 $A4 adr LSB adr LSB adr LSB $00 $00 $00 $00 $00 data byte in $00 data byte in data byte in data byte in data byte in $28 $20 $A0 $58 $30 $50 $58 $50 $38 adr MSB adr MSB adr MSB $00 $00 $00 $08 $08 $00 adr LSB adr LSB adr LSB $00 adr LSB $00 $00 $00 $00 high data byte out low data byte out data byte out data byte out data byte out data byte out data byte out data byte out data byte out $4D $48 $40 $C1 $00 adr MSB adr MSB adr MSB Extended adr adr LSB adr LSB adr LSB $00 high data byte in low data byte in data byte in Byte 1 $AC $AC $F0 Byte 2 $53 $80 $00 Byte 3 $00 $00 $00 Byte4 $00 $00 data byte out
Not all instructions are applicable for all parts. a = address Bits are programmed `0', unprogrammed `1'. To ensure future compatibility, unused Fuses and Lock bits should be unprogrammed (`1') . Refer to the corresponding section for Fuse and Lock bits, Calibration and Signature bytes and Page size. Instructions accessing program memory use word address. This address may be random within the page range. See htt://www.atmel.com/avr for Application Notes regarding programming and programmers.
214
8042A-AVR-07/09
ATmega16HVB/32HVB
If the LSB in RDY/BSY data byte out is `1', a programming operation is still pending. Wait until this bit returns `0' before the next instruction is carried out. Within the same page, the low data byte must be loaded prior to the high data byte. After data is loaded to the page buffer, program the EEPROM page, see Figure 30-2 on page 215. Figure 30-2. Serial Programming Instruction example
Serial Programming Instruction
Load Program Memory Page (High/Low Byte)/ Load EEPROM Memory Page (page access) Write Program Memory Page/ Write EEPROM Memory Page
Byte 1
Byte 2
A Adr MSB
Bit 15 B
Byte 3
Adr LSB
0
Byte 4
Byte 1
Byte 2
Adr MSB
Bit 15 B
Byte 3
Adr LSB r B
0
Byte 4
Page Buffer
Page Offset
Page 0
Page 1
Page 2
Page Number
Page N-1
Program Memory/ EEPROM Memory
215
8042A-AVR-07/09
ATmega16HVB/32HVB
30.7
Parallel Programming
This section describes parameters, pin mapping, and commands used to parallel program and verify Flash Program memory, EEPROM Data memory, Memory Lock bits, and Fuse bits in the ATmega16HVB/32HVB. Pulses are assumed to be at least 250 ns unless otherwise noted.
30.7.1
Considerations for Efficient Programming The loaded command and address are retained in the device during programming. For efficient programming, the following should be considered. * The command needs only be loaded once when writing or reading multiple memory locations. * Skip writing the data value 0xFF, that is the contents of the entire EEPROM (unless the EESAVE Fuse is programmed) and Flash after a Chip Erase. Address high byte needs only be loaded before programming or reading a new 256 word window in Flash or 256 byte EEPROM. This consideration also applies to Signature bytes reading.
30.7.2
Signal Names In this section, some pins of the ATmega16HVB/32HVB are referenced by signal names describing their functionality during parallel programming, see Figure 30-3 on page 216 and Table 30-13 on page 217. Pins not described in the following table are referenced by pin names. The XA1/XA0 pins determine the action executed when the XTAL1 pin is given a positive pulse. The bit coding is shown in Table 30-15 on page 217. When pulsing WR or OE, the command loaded determines the action executed. The different Commands are shown in Table 30-16 on page 218. Table 32-18 on page 239 shows the Parallel programming characteristics. Figure 30-3. Parallel Programming
+11.5 - 12.5V +3.0 - 3.3V
RESET
VCC
PAGEL BS2 BS1
X1 X0 OE XTAL1 WR GND VFET (0V) DATA[7:0] RDY/BSY
216
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 30-13. Pin Name Mapping
Signal Name in Programming Mode RDY/BSY BS1 BS2 PAGEL RESET DATA WR OE XTAL XA0 XA1 Pin Name PA0 PA1 PA2 PA3 RESET PB7:0 PC0 PC1 PC2 PC3 PC4 I/O O I I I I I/O I I I I I XTAL Action Bit 0 XTAL Action Bit 1 Bi-directional Data bus (Output when OE is low). Write Pulse (Active low) Output Enable (Active low). Function 0: Device is busy programming 1: Device is ready for new command. Byte Select 1 ("0" selects low byte, "1" selects high byte). Byte Select 2 ("0" selects low byte, "1" selects 2'nd high byte). Program Memory and EEPROM data Page Load.
Table 30-14. Pin Values Used to Enter Programming Mode
Pin PB3 PB2 PB1 PB0 Symbol Prog_enable[3] Prog_enable[2] Prog_enable[1] Prog_enable[0] Value 0 0 0 0
Table 30-15. XA1 and XA0 Coding
XA1 0 0 1 1 XA0 0 1 0 1 Action when XTAL1 is Pulsed Load Flash or EEPROM Address (High or low address byte determined by BS1). Load Data (High or Low data byte for Flash determined by BS1). Load Command No Action, Idle
217
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 30-16. Command Byte Bit Coding
Command Byte 1000 0000 0100 0000 0010 0000 0001 0000 0001 0001 0000 1000 0000 0100 0000 0010 0000 0011 Command Executed Chip Erase Write Fuse bits Write Lock bits Write Flash Write EEPROM Read Signature Bytes and Calibration byte Read Fuse and Lock bits Read Flash Read EEPROM
30.7.3
Enter Programming Mode The following algorithm puts the device in parallel programming mode: 1. Make sure the chip is started as explained in "Power-on Reset and Charger Connect" on page 43. 2. Set RESET to "0" and toggle XTAL1 at least six times. 3. Set the Prog_enable pins listed in Table 30-14 on page 217 to "0000" and wait at least 100 ns. 4. Apply 11.5 - 12.5V to RESET. Any activity on Prog_enable pins within 100 ns after +12V has been applied to RESET, will cause the device to fail entering programming mode. 5. Wait at least 50 s before sending a new command.
30.7.4
Chip Erase The Chip Erase will erase the Flash and EEPROM(1) memories plus Lock bits. The Lock bits are not reset until the program memory has been completely erased. The Fuse bits are not changed. A Chip Erase must be performed before the Flash and/or EEPROM are reprogrammed.
Note: 1. The EEPRPOM memory is preserved during Chip Erase if the EESAVE Fuse is programmed.
Load Command "Chip Erase" 1. Set XA1, XA0 to "10". This enables command loading. 2. Set BS1 to "0". 3. Set DATA to "1000 0000". This is the command for Chip Erase. 4. Give XTAL1 a positive pulse. This loads the command. 5. Give WR a negative pulse. This starts the Chip Erase. RDY/BSY goes low. 6. Wait until RDY/BSY goes high before loading a new command.
218
8042A-AVR-07/09
ATmega16HVB/32HVB
30.7.5 Programming the Flash The Flash is organized in pages, see Table 30-7 on page 211. When programming the Flash, the program data is latched into a page buffer. This allows one page of program data to be programmed simultaneously. The following procedure describes how to program the entire Flash memory: A. Load Command "Write Flash" 1. Set XA1, XA0 to "10". This enables command loading. 2. Set BS1 to "0". 3. Set DATA to "0001 0000". This is the command for Write Flash. 4. Give XTAL1 a positive pulse. This loads the command. B. Load Address Low byte 1. Set XA1, XA0 to "00". This enables address loading. 2. Set BS1 to "0". This selects low address. 3. Set DATA = Address low byte (0x00 - 0xFF). 4. Give XTAL1 a positive pulse. This loads the address low byte. C. Load Data Low Byte 1. Set XA1, XA0 to "01". This enables data loading. 2. Set DATA = Data low byte (0x00 - 0xFF). 3. Give XTAL1 a positive pulse. This loads the data byte. D. Load Data High Byte 1. Set BS1 to "1". This selects high data byte. 2. Set XA1, XA0 to "01". This enables data loading. 3. Set DATA = Data high byte (0x00 - 0xFF). 4. Give XTAL1 a positive pulse. This loads the data byte. E. Latch Data 1. Set BS1 to "1". This selects high data byte. 2. Give PAGEL a positive pulse. This latches the data bytes. (See Figure 30-5 for signal waveforms) F. Repeat B through E until the entire buffer is filled or until all data within the page is loaded. While the lower bits in the address are mapped to words within the page, the higher bits address the pages within the FLASH. This is illustrated in Figure 30-4 on page 220. Note that if less than eight bits are required to address words in the page (pagesize < 256), the most significant bit(s) in the address low byte are used to address the page when performing a Page Write. G. Load Address High byte 1. Set XA1, XA0 to "00". This enables address loading. 2. Set BS1 to "1". This selects high address. 3. Set DATA = Address high byte (0x00 - 0xFF). 4. Give XTAL1 a positive pulse. This loads the address high byte.
219
8042A-AVR-07/09
ATmega16HVB/32HVB
H. Program Page 1. Give WR a negative pulse. This starts programming of the entire page of data. RDY/BSY goes low. 2. Wait until RDY/BSY goes high (See Figure 30-5 for signal waveforms). I. Repeat B through H until the entire Flash is programmed or until all data has been programmed. J. End Page Programming 1. 1. Set XA1, XA0 to "10". This enables command loading. 2. Set DATA to "0000 0000". This is the command for No Operation. 3. Give XTAL1 a positive pulse. This loads the command, and the internal write signals are reset. Figure 30-4. Addressing the Flash Which is Organized in Pages(1)
PCMSB PROGRAM COUNTER
PCPAGE
PAGEMSB
PCWORD
PAGE ADDRESS WITHIN THE FLASH PROGRAM MEMORY
PAGE
WORD ADDRESS WITHIN A PAGE
PAGE INSTRUCTION WORD PCWORD[PAGEMSB:0]: 00 01 02
PAGEEND
Note:
1. PCPAGE and PCWORD are listed in Table 30-7 on page 211.
220
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 30-5. Programming the Flash Waveforms(1)
F
A
DATA 0x10
B
ADDR. LOW
C
DATA LOW
D
DATA HIGH
E
XX
B
ADDR. LOW
C
DATA LOW
D
DATA HIGH
E
XX
G
ADDR. HIGH
H
XX
XA1
XA0
BS1
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
BS2
Note:
1. "XX" is don't care. The letters refer to the programming description above.
30.7.6
Programming the EEPROM The EEPROM is organized in pages, see Table 30-8 on page 211. When programming the EEPROM, the program data is latched into a page buffer. This allows one page of data to be programmed simultaneously. The programming algorithm for the EEPROM data memory is as follows (refer to "Programming the Flash" on page 219 for details on Command, Address and Data loading): 1. A: Load Command "0001 0001". 2. G: Load Address High Byte (0x00 - 0xFF). 3. B: Load Address Low Byte (0x00 - 0xFF). 4. C: Load Data (0x00 - 0xFF). 5. E: Latch data (give PAGEL a positive pulse). K: Repeat 3 through 5 until the entire buffer is filled. L: Program EEPROM page 1. Set BS to "0". 2. Give WR a negative pulse. This starts programming of the EEPROM page. RDY/BSY goes low. 3. Wait until to RDY/BSY goes high before programming the next page (See Figure 30-6 for signal waveforms).
221
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 30-6. Programming the EEPROM Waveforms
K
A
DATA 0x11
G
ADDR. HIGH
B
ADDR. LOW
C
DATA
E
XX
B
ADDR. LOW
C
DATA
E
XX
L
XA1
XA0
BS1
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
BS2
30.7.7
Reading the Flash The algorithm for reading the Flash memory is as follows (refer to "Programming the Flash" on page 219 for details on Command and Address loading): 1. A: Load Command "0000 0010". 2. G: Load Address High Byte (0x00 - 0xFF). 3. B: Load Address Low Byte (0x00 - 0xFF). 4. Set OE to "0", and BS1 to "0". The Flash word low byte can now be read at DATA. 5. Set BS to "1". The Flash word high byte can now be read at DATA. 6. Set OE to "1".
30.7.8
Reading the EEPROM The algorithm for reading the EEPROM memory is as follows (refer to "Programming the Flash" on page 219 for details on Command and Address loading): 1. A: Load Command "0000 0011". 2. G: Load Address High Byte (0x00 - 0xFF). 3. B: Load Address Low Byte (0x00 - 0xFF). 4. Set OE to "0", and BS1 to "0". The EEPROM Data byte can now be read at DATA. 5. Set OE to "1".
222
8042A-AVR-07/09
ATmega16HVB/32HVB
30.7.9 Programming the Fuse Low Bits The algorithm for programming the Fuse Low bits is as follows (refer to "Programming the Flash" on page 219 for details on Command and Data loading): 1. A: Load Command "0100 0000". 2. C: Load Data Low Byte. Bit n = "0" programs and bit n = "1" erases the Fuse bit. 3. Give WR a negative pulse and wait for RDY/BSY to go high. 30.7.10 Programming the Fuse High Bits The algorithm for programming the Fuse High bits is as follows (refer to "Programming the Flash" on page 219 for details on Command and Data loading): 1. A: Load Command "0100 0000". 2. C: Load Data Low Byte. Bit n = "0" programs and bit n = "1" erases the Fuse bit. 3. Set BS1 to "1" and BS2 to "0". This selects high data byte. 4. Give WR a negative pulse and wait for RDY/BSY to go high. 5. Set BS1 to "0". This selects low data byte. Figure 30-7. Programming the FUSES Waveforms
Write Fuse Low byte A
DATA
0x40
Write Fuse high byte A C
DATA XX
Write Extended Fuse byte A
0x40
C
DATA XX
C
DATA XX
0x40
XA1
XA0
BS1
BS2
XTAL1
WR
RDY/BSY
RESET +12V
OE
PAGEL
30.7.11
Programming the Lock Bits The algorithm for programming the Lock bits is as follows (refer to "Programming the Flash" on page 219 for details on Command and Data loading): 1. A: Load Command "0010 0000". 2. C: Load Data Low Byte. Bit n = "0" programs the Lock bit. If LB mode 3 is programmed (LB1 and LB2 is programmed), it is not possible to program the Boot Lock bits by any External Programming mode. 3. Give WR a negative pulse and wait for RDY/BSY to go high. The Lock bits can only be cleared by executing Chip Erase.
223
8042A-AVR-07/09
ATmega16HVB/32HVB
30.7.12 Reading the Fuse and Lock Bits The algorithm for reading the Fuse and Lock bits is as follows (refer to "Programming the Flash" on page 219 for details on Command loading): 1. A: Load Command "0000 0100". 2. Set OE to "0", BS2 to "0" and BS1 to "0". The status of the Fuse Low bits can now be read at DATA ("0" means programmed). 3. Set OE to "0", BS2 to "1" and BS1 to "1". The status of the Fuse High bits can now be read at DATA ("0" means programmed). 4. Set OE to "0", BS2 to "0" and BS1 to "1". The status of the Lock bits can now be read at DATA ("0" means programmed). 5. Set OE to "1". Figure 30-8. Mapping Between BS1, BS2 and the Fuse and Lock Bits During Read
Fuse Low Byte 0
0 Extended Fuse Byte BS2 Lock Bits 0 1 1 DATA
Fuse High Byte BS2
1
BS1
30.7.13
Reading the Signature Bytes The algorithm for reading the Signature bytes is as follows (refer to "Programming the Flash" on page 219 for details on Command and Address loading): 1. A: Load Command "0000 1000". 2. B: Load Address Low Byte (0x00 - 0x02). 3. Set OE to "0", and BS to "0". The selected Signature byte can now be read at DATA. 4. Set OE to "1".
30.7.14
Reading the Calibration Byte The algorithm for reading the Calibration byte is as follows (refer to "Programming the Flash" on page 219 for details on Command and Address loading): 1. A: Load Command "0000 1000". 2. B: Load Address Low Byte, 0x00. 3. Set OE to "0", and BS1 to "1". The Calibration byte can now be read at DATA. 4. Set OE to "1".
224
8042A-AVR-07/09
ATmega16HVB/32HVB
Optional secondary protection and fuse blow circuitry
Q3
Q2
+
F1 R15 D2 SENSE VCC R18 VC1 ICT C10 R2 VC2 C2 R1 VC3 C1 C12 R16 PC2 FUSE STATUS VSS CO D1 PB0 FUSE BLOW C11 Q4 R17 PVT OC VFET OD C3 VCC R19 R20 C4 R3
Pack+
Q1
R4
R21
D3
S-8244
BATT
R23
PC0/EXT_PROT
VCC
R22
R24
R25
PC1
SYS PRESENT
R9 PV4 CELL4 R8 PV3 C7 CELL3 R7 PV2 C6 CELL2 R6 PV1 CELL1 R5 NV C5 C8
D4
R26
PC3/SDA
SMBDATA
PC4/SCL
SMBCLK
D5
R27
ATmega16HVB/32HVB
R28
R29
PC5
PA3 R13 PPI R11 PI
PA2
PB1/CKOUT
SW1 C9 R12 NI R14 NNI PA0/ADC0/SGND
PB2
PB3
D6
VCC
PB4
D7
PB5 R32 R33 PA1/ADC1/SGND VREF C17 VREFGND VREG VCC VCLMP10 RESET
D8
PB6
D9
R30
PB7
D10
Figure 31-1. Operating Circuit
31. Operating Circuit
R31 C16 C14
VCC
C13
C18
C15
R10
-
Pack-
225
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 31-1.
Symbol
Bill of Materials
Number 6 4 4 1 1 1 1 1 1 1 1 1 1 5 1 1 2 1 4 5 1 2 7 1 2 1 1 1 2 2 1 1 2 Description Capacitor, ceramic, 0.1 - 1.0 F, 50V, X7R Capacitor, ceramic, 0.01 - 0.5 F, 50V, X7R Capacitor, ceramic, 0.1 F, 50V, X7R Capacitor, ceramic, 2.2 - 4.7 F, 10V, X7R Capacitor, ceramic, 1 - 22 F, 10V, X7R Capacitor, ceramic, 0.47 F, 10V, X7R Capacitor, ceramic, 22 nF, 50V, X7R Diode, signal Diode, double, Shottky Diode, signal Diode, Zener, value from design considerations Diode, Zener, 5V6 Diode, double, Zener, 5V6 LEDs Chemical fuse N-FET, 50V, 0.22A N-FET, 30V, 10A N-FET, 20V, 1.3A Resistor, chip, 1-10 k, 1/16W, 5% Resistor, chip, 10-1000, 1/16W, 5% Sense resistor, 1-10 m, 1W, 1% Resistor, chip, 10-500, 1/16W, 5% Resistor, chip 1 k, 1/16W, 5% Resistor, chip, 100-1000, 1/16W, 5% Resistor, chip 200 k, 1/16W, 5% Resistor, value from design considerations Resistor, value from design considerations Resistor, chip 1 k, 1/16W, 5% Resistor, chip 100 , 1/16W, 5% Resistor, chip 1 M, 1/16W, 5% Resistor, chip 820 , 1/16W, 5% Resistor, chip 10 k, 1/16W, 5% NTC thermistor, 10 k, B = 3000 - 4000
C1-C4, C10, C11 C5-C8 C9, C12, C13, C15 C14 C16 C17 C18 D1 D2 D4 D3 D4 D5 D6-D10 F1 Q1 Q2, Q3 Q4 R1-R4 R5-R9 R10 R11, R12 R13, R14, R18, R19, R20, R21, R25 R15 R16, R17 R22 R23 R24 R26, R27 R28, R29 R30 R31 R32, R33
226
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 31-1.
Symbol SW U1 U2
Bill of Materials
Number 1 1 1 Description Switch, push button ATmega32HVB (Atmel) S-8244 secondary protection device (Seiko Instruments)
227
8042A-AVR-07/09
ATmega16HVB/32HVB
32. Electrical Characteristics
32.1 Absolute Maximum Ratings*
*NOTICE: Stresses beyond those listed under "Absolute Maximum Ratings" may cause permanent damage to the device. This is a stress rating only and functional operation of the device at these or other conditions beyond those indicated in the operational sections of this specification is not implied. Exposure to absolute maximum rating conditions for extended periods may affect device reliability.
Operating Temperature.................................... -40C to +85C Storage Temperature ..................................... -65C to +150C Voltage on PA0 - PA3, PI, NI, PPI and NNI with respect to Ground ............................. -0.5V to VREG +0.5V Voltage on PB0 - PB7 with respect to Ground ............................. -0.5V to VCC +0.5V Voltage on PC0 - PC4, PV1, and NV with respect to Ground................-0.5V to + 6.0V Voltage on PC5, BATT, PVT, VFET, OC, OD, PV4, PV3, and PV2 with respect to Ground........................-0.5V to + 35V Voltage on VCLMP10 and RESET with respect to Ground ......................................-0.5V to + 13V Maximum Operating Voltage on VREG and VCC............. 4.5V Maximum Operating Voltage on VFET .............................. 25V
32.2
Supply Current Characteristics
TA= 25C unless otherwise noted. Parameter Active current VFET=16V, CPU clock=1MHz, All PRR bits set Idle current VFET=16V, CPU clock=1MHz, All PRR bits set VFET=16V, CPU clock=1MHz, All PRR bits except PRVADC are set, VADC enabled. VFET=16V, Only WDT enabled, DUVR mode disabled. Power-save current VFET=16V, WDT, CC-ADC, OC, OD and Battery Protection enabled, DUVR mode disabled. VFET=6V 760 215 350 A 28 85 <1 46 138 2 1000 293 Condition VFET=16V, CPU clock=8MHz, All PRR bits set Min Typ 3.75 Max 5 Unit mA
Table 32-1.
Symbol
IVFET
ADCNRM current
Power-off current
228
8042A-AVR-07/09
ATmega16HVB/32HVB
32.3 NFET Driver Characteristics
TA= 25C unless otherwise noted. Parameter OC pin on voltage relative to PVT voltage Condition OC enabled, VFET=16V VOC,ON OC enabled, VFET=10V OC enabled, VFET=4V OD enabled, VFET=16V VOD,ON OD pin on voltage relative to BATT voltage OC pin off voltage realtive to GND OD pin off voltage realtive to GND V(OC-PVT)=0 to 2V, Ceq=4.7nF, VFET=16V V(OC-PVT)=0 to 2V, Ceq=4.7nF, VFET=10V tr,OC Rise time on OC pin V(OC-PVT)=0 to 2V, Ceq=4.7nF, VFET=6V V(OC-PVT)=2 to 4V, Ceq=4.7nF, VFET=16V V(OC-PVT)=2 to 4V, Ceq=4.7nF, VFET=10V V(OC-PVT)=2 to 4V, Ceq=4.7nF, VFET=6V V(OD-BATT)=0 to 2V, Ceq=4.7nF, VFET=16V V(OD-BATT)=0 to 2V, Ceq=4.7nF, VFET=10V tr,OD Rise time on OD pin V(OD-BATT)=0 to 2V, Ceq=4.7nF, VFET=6V V(OD-BATT)=2 to 4V, Ceq=4.7nF, VFET=16V V(OD-BATT)=2 to 4V, Ceq=4.7nF, VFET=10V V(OD-BATT)=2 to 4V, Ceq=4.7nF, VFET=6V tf,OC tf,OD VVFET,DUVR Note: Fall time on OC pin Fall time on OD pin Regulated VFET voltage in DUVR mode V(OD-PVT)=VOC,ON to 0V V(OD-BATT)=VOD,ON to 0V DUVR enabled, VREF=1.1V 4.1 OD enabled, VFET=10V OD enabled, VFET=4V VOC,OFF VOD,OFF Min. Typ. 13 13 6 13 V 13 6 0.0 0.0 0.8 1.1 3 1 1.2 1.3 ms 0.8 1.1 3 1 1.2 1.3 50 ns 50 4.9 V Max. Units
Table 32-2.
Symbol
The NFET drivers require a minimum total cell voltage of 6V or higher or a charger connected to turn-on the FETs. Note that this limit only applies if the FET is disabled in advanced. If the FET is already enabled, the FET will be fully operational in the entire voltage range of the device (4-25V).
229
8042A-AVR-07/09
ATmega16HVB/32HVB
32.4 Reset Characteristics
TA= -40 to 85C unless otherwise noted. Parameter Power-on Threshold Voltage (rising) VPOT tRST VBOT VHYST Notes:
(1)
Table 32-3.
Symbol
Condition
Min 4.5 4.5
Typ
Max 7
Units V
Power-on Threshold Voltage (falling)(1)(2) Minimum pulse width on RESET Pin Brown-Out Detection (BOD) Trigger Level BOD Level Hysteresis TA= 25C TA= 25C
6.3 900 2.9 50 ns V mV
1. The voltage at the Pack + terminal will be slightly higher than VPOT when the chip is enabled. This is because of an internal Pull-down current on the BATT pin in the range 50 - 150 uA and the RBATT resistor connected between the Pack + terminal and the BATT pin. RBATT = 1k gives a voltage drop 0.05 - 0.15V. 2. The power-on reset will not work unless the voltage has been below VPOT (falling) after a power-off condition.
32.5
Voltage Regulator Characteristics
TA= -40 to 85C unless otherwise noted. Parameter Condition VFET=16.8V, IOUT=20mA Min 3.1 3.1 3.1 V 3.3 TA= 25C 2.65 3.7 Typ Max Unit
Table 32-4.
Symbol
VVREG
Regulator Output Voltage
VFET=6V, IOUT=20mA VFET=4V, IOUT=7mA
VRSCL VBLOD
Voltage Regulator Short- circuit Level at VFET pin Voltage Regulator Black-out Detection Level at VREG pin
32.6
Voltage reference and Temperature Sensor Characteristics
TA= -40 to 85C unless otherwise noted. Condition Min Typ 1.100 After factory calibration, TA= 25C TA = -40 - 85C TA = 0 - 60C 0.1 60 25 2 s CREG=2.2f, BGCRR write 5 0.6 5 mV/K K 0.2 90 ppm/K 50 Max Unit V %
Table 32-5.
Parameter
Reference Voltage Ref. Voltage Accuracy(1) Temperature Drift(1)(2) VREF calibration Hold Off Time VPTAT, Voltage Proportional to Absolute Temperature(2) VPTAT Absolute Accuracy(3) Notes:
CREG=2.2F, BGCCR write
1. Calibration is done in Atmel factory test. Software should calibrate the VREF by writing the BGCRR and BGCCR registers with the calibration values stored in the signature row. 2. This value is not tested in production.
230
8042A-AVR-07/09
ATmega16HVB/32HVB
3. The measured VPTAT voltage must be scaled with the calibration value stored in the VPTAT Calibration Register to get the absolute temperature. The design target accuracy for this parameter assumes an exact calibration temperature. Actual accuracy of this parameter after calibration in Atmel factory test remains to be determined.
32.7
32.7.1
ADC Characteristics
Voltage ADC Characteristics
TA= -40 to 85C unless otherwise noted. Condition clkVADC = 1 MHz Min Typ 519 12 263 1.42 ADC0, ADC1 1 1 2 0 1.8 VPV1-GND>1.8V VPV2-GND>1.8V VPV3-GND>1.8V ADC0, ADC1 0 0 0 1 1 5 6 7 15 LSB LSB 3 3 5 1 5 5 5 5 V LSB Max Unit s Bits V/LSB mV/LSB
Table 32-6.
Parameter
Conversion Time Resolution Gain ADC0/1 (Un-scaled) Gain Cell Inputs (x0.2)
INL(2)
CELL1, CELL2, CELL3 CELL4
Input Voltage range ADC0, ADC1, VTEMP Input Voltage range CELL1 Input Voltage range CELL2 Input Voltage range CELL3 Input Voltage range CELL4
Offset drift(1)(2)
CELL1, CELL2, CELL3 CELL4 ADC0, ADC1
Gain drift
(1)(2)
CELL1, CELL2, CELL3 CELL4
Notes:
1. Value is after Atmel factory offset and gain compensation in production (for details, see Table 29-3, "Signature Row Addressing.," on page 199) and it includes drift over the whole temperature range. 2. Value not tested in production but guarantied by design and characterization.
231
8042A-AVR-07/09
ATmega16HVB/32HVB
32.7.2 Coulomb Counter ADC Characteristics
TA= -40 to 85C unless otherwise noted. Condition Instantaneous conversion, clkCC-ADC=32kHz Accumulated conversion CADAS=11, clkCC-ADC=32kHz Instantaneous conversion Resolution Accumulated conversion Accumulated conversion, CADVSE=0 Accumulated conversion, CADVSE=1 Gain Instantaneous conversion, CADVSE=0 Instantaneous conversion, CADVSE=1 CADVSE = 0 Input voltage Range CADVSE = 1 INL
(1)
Table 32-7.
Parameter
Min
Typ 3.9 1 13
Max
Unit ms s Bits
Conversion Time
18 1.67 0.84 V/LSB 53.7 26.9 -200 -100 0.005 -7 30 0.4 1 % 0.1 200 100 0.003 % FSR V nV/C mV
TA= 0- 60C Accumulated conversion, TA= 25C Accumulated conversion
Offset Error(2) Offset Error Drift(1)(2) Gain Error
(1)(3) (1)
Gain Error Drift Notes:
1. Values based on characterization data. 2. After software offset compensation, using the polarity switching (CADPOL) feature. 3. Value includes drift over the whole temperature range.
32.8
Clock Characteristics
TA= -40 to 85C unless otherwise noted. Parameter Frequency Condition After factory calibration at TA=25C With run-time calibration with OSI interface and Slow RC Oscillator as calibration clock 91 131 1 % Frequency prediction error Ultra Low Power RC Oscillator(1) Frequency(3) Frequency drift(2) 89 0.5 128 6 167 kHz % Min 7.92 Typ 8 Max 8.08 Unit MHz
Table 32-8.
Calibrated Fast RC Oscillator Frequency drift(2) Frequency(3) Slow RC Oscillator(1) Frequency drift
3 171
% kHz
Notes:
1. The frequency is stored in the Value after factory calibration at 85C 2. Value not tested in production, but it is guarantied by design and characterization over the whole temperature range. 3. The actual oscillator frequency is measured in production and stored in the device signature row (for details, see "Reading the Signature Row from Software" on page 199).
232
8042A-AVR-07/09
ATmega16HVB/32HVB
32.9 Cell Balancing Characteristic
TA= 25C unless otherwise noted. Condition Battery cell Voltage VCELL =4.2V, V-ADC filter resistance=470 Min Typ 4 Max Unit mA
Table 32-9.
Parameter
Balancing Current
32.10 Battery Protection Characteristics
Table 32-10. TA= -40 to 85C unless otherwise noted.
Symbol Parameter Short Circuit Detection level accuracy(1)(2) Condition VSCD=20mV (min level) VSCD=VNNI-VPPI VSCD=150mV VSCD=310mV(max) VCOCD,DOCD=20mV (min level) VCOCD=VPPI-VNNI, VDOCD=VNNI-VPPI Charge/Discharge Over Current Detection level accuracy(1)(2) VCOCD,DOCD=150mV VCOCD,DOCD=310mV(max) VCHCD=VPPI-VNNI, VDHCD=VNNI-VPPI Charge/Discharge High Current Detection Detection level accuracy(1)(2) VCHCD,DHCD=20mV (min level) VCHCD,DHOCD=150mV VCHCD,DHCD=310mV(max) Min 14 130 280 15 130 280 15 130 280 Typ 20 150 310 20 150 310 20 150 310 Max 26 170 340 25 170 340 25 170 340 mV Unit
Notes:
1. Value includes drift in the internal Voltage Reference after VREF factory calibration. 2. Levels in charge and discharge direction can be configured independent of each other.
32.11 External Interrupt Characteristics
Table 32-11. Asynchronous External Interrupt Characteristics
Symbol tINT Parameter Minimum pulse width for asynchronous external interrupt Condition Min Typ 50 Max Units ns
233
8042A-AVR-07/09
ATmega16HVB/32HVB
32.12 General I/O Lines Characteristics
32.12.1 Port A and B Characteristics
Table 32-12. TA = -40 to 85C, VCC = 3.3V (unless otherwise noted)
Symbol VIL VIL1 VIH VIH1 VOL VOH IIL IIH RRST RPU Notes: Parameter Input Low Voltage, Except RESET pin Input Low Voltage, RESET pin Input High Voltage, Except RESET pin Input High Voltage, RESET pin Output Low Voltage Output High Voltage Input Leakage Current I/O Pin Input Leakage Current I/O Pin Reset Pull-up Resistor I/O Pin Pull-up Resistor IOL = 5mA IOH = 2 mA Pin low (absolute value) Pin high (absolute value) 30 20 2.3 1 A 1 60 k 50 0.6VCC(2) 0.9VCC(2) Condition Min. -0.5 Typ. Max. 0.3VCC(1) 0.3VCC(1) VCC + 0.5 VCC + 0.5 0.5 V Units
1. "Max" means the highest value where the pin is guaranteed to be read as low 2. "Min" means the lowest value where the pin is guaranteed to be read as high 3. Although each I/O port can sink more than the test conditions (5 mA at VCC = 3.3V) under steady state conditions (non-transient), the following must be observed: - The sum of all IOL should not exceed 20 mA. If IOL exceeds the test condition, VOL may exceed the related specification. Pins are not guaranteed to sink current greater than the listed test condition. 4. Although each I/O port can source more than the test conditions (2 mA at VCC = 3.3V) under steady state conditions (nontransient), the following must be observed: - The sum of all IOH should not exceed 2 mA.
32.12.2
Port C Characteristics
Table 32-13. PC0-PC4 Characteristics
Symbol VIL VIH VOL(1) Note: Parameter Input Low-voltage Input High-voltage Output Low-voltage 350 A sink current Condition Min -0.5 2.1 0 Max 0.8 5.5 0.4 V Units
1. This values is based on characterization and is not tested in production.
Table 32-14. PC5 Characteristic
Symbol VOL Parameter Output Low-voltage Condition 500 A sink current Min 0 Max 0.2 Units V
234
8042A-AVR-07/09
ATmega16HVB/32HVB
32.13 2-wire Serial Interface Characteristics
Table 32-15 on page 235 describes the requirements for devices connected to the Two-wire Serial Bus. The ATmega16HVB/32HVB Two-wire Serial Interface meets or exceeds these requirements under the noted conditions. Timing symbols refer to Figure 32-1 on page 236. Table 32-15. Two-wire Serial Bus Requirements
Symbol VIL VIH VOL(1)
tr (1) (1) tof (1) tSP
Parameter Input Low-voltage Input High-voltage Output Low-voltage Rise Time for both SDA and SCL Output Fall Time from VIHmin to VILmax Spikes Suppressed by Input Filter Input Current each I/O Pin Capacitance for each I/O Pin SCL Clock Frequency Value of Pull-up resistor Hold Time (repeated) START Condition Low Period of the SCL Clock High period of the SCL clock Set-up time for a repeated START condition Data hold time Data setup time Setup time for STOP condition Bus free time between a STOP and START condition
Condition
Min -0.5 2.1
Max 0.8 5.5 0.4 300
Units
V
350 A sink current
0
Cb < 400 pF(2) 0 0.1VBUS < Vi < 0.9VBUS fCK(3) > max(16fSCL, 450 kHz)(4) fSCL 100 kHz fSCL 100 kHz fSCL 100 kHz fSCL 100 kHz fSCL 100 kHz fSCL 100 kHz fSCL 100 kHz fSCL 100 kHz fSCL 100 kHz -5 - 0 V BUS - 0,4V -----------------------------350A 4.0 4.7 4.0 4.7 0.3 250 4.0 4.7
250 50 5 10 100 V BUS - 0,4V -----------------------------100A - - - - 3.45 - - -
ns
Ii Ci(1) fSCL Rp tHD;STA tLOW tHIGH tSU;STA tHD;DAT tSU;DAT tSU;STO tBUF Notes: 1. 2. 3. 4.
A pF kHz
s
In ATmega16HVB/32HVB, this parameter is characterized and not tested. Cb = capacitance of one bus line in pF. fCK = CPU clock frequency This requirement applies to all ATmega16HVB/32HVB Two-wire Serial Interface operation. Other devices connected to the Two-wire Serial Bus need only obey the general fSCL requirement.
235
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 32-1. Two-wire Serial Bus Timing
tof tLOW SCL tSU;STA SDA tHD;STA tHD;DAT tSU;DAT tSU;STO tHIGH tLOW tr
tBUF
32.14 SPI Timing Characteristics
See Figure 32-2 on page 237 and Figure on page 237 for details. Table 32-16. SPI Timing Parameters
Description 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 Note: SCK period SCK high/low Rise/Fall time Setup Hold Out to SCK SCK to out SCK to out high SS low to out SCK period SCK high/low
(1)
Mode Master Master Master Master Master Master Master Master Slave Slave Slave Slave Slave Slave Slave Slave Slave Slave
Min
Typ
Max
Units
See Figure 50% duty 3.6 10 10 0.5 * tsck 10 10 15 4 * tck + 40 ns 2 * tck + 20 ns 1.6 10 tck 15 20 10 20 ns s ns
Rise/Fall time Setup Hold SCK to out SCK to SS high SS high to tri-state SS low to SCK
1. Refer to "Serial Programming" on page 211 for serial programming requirements.
236
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 32-2. SPI Interface Timing Requirements (Master Mode)
SS
6 1
SCK (CPOL = 0)
2 2
SCK (CPOL = 1)
4 5 3
MISO (Data Input)
MSB 7
...
LSB 8
MOSI (Data Output)
MSB
...
LSB
SPI Interface Timing Requirements (Slave Mode)
SS
9 10 16
SCK (CPOL = 0)
11 11
SCK (CPOL = 1)
13 14 12
MOSI (Data Input)
MSB 15
...
LSB 17
MISO (Data Output)
MSB
...
LSB
X
32.15 Serial Programming Characteristics
Figure 32-3. Serial Programming Timing
MOSI tOVSH SCK MISO tSLIV tSHSL tSHOX tSLSH
237
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 32-4. Serial Programming Waveforms
SERIAL DATA INPUT (MOSI) SERIAL DATA OUTPUT (MISO) SERIAL CLOCK INPUT (SCK)
SAMPLE
MSB
LSB
MSB
LSB
Table 32-17. Serial Programming Characteristics, TA = -40C to 85C, VCC = 3.3V (Unless Otherwise Noted)
Symbol 1/tCLCL tCLCL tSHSL tSLSH tOVSH tSHOX tSLIV Note: Parameter Oscillator Frequency (ATmega16HVB/32HVB) Oscillator Period (ATmega16HVB/32HVB) SCK Pulse Width High SCK Pulse Width Low MOSI Setup to SCK High MOSI Hold after SCK High SCK Low to MISO Valid Min 0 125 2.2 tCLCL(1) 2.2 tCLCL(1) tCLCL 2 tCLCL 15 ns Typ Max 8 Units MHz
1. 2.2 tCLCL for fck < 12 MHz, 3 tCLCL for fck >= 12 MHz
32.16 Parallel Programming Characteristics
Figure 32-5. Parallel Programming Timing, Including some General Timing Requirements
tXLWL XTAL1 tDVXH Data & Contol (DATA, XA0/1, BS1, BS2) tBVPH PAGEL WR RDY/BSY tWLRH tPHPL tWLWH tPLWL
WLRL
tXHXL tXLDX
tPLBX t BVWL
tWLBX
238
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 32-6. Parallel Programming Timing, Loading Sequence with Timing Requirements(1)
LOAD ADDRESS (LOW BYTE) LOAD DATA (LOW BYTE)
t XLXH
LOAD DATA LOAD DATA (HIGH BYTE)
tXLPH tPLXH
LOAD ADDRESS (LOW BYTE)
XTAL1
BS1
PAGEL
DATA
ADDR0 (Low Byte)
DATA (Low Byte)
DATA (High Byte)
ADDR1 (Low Byte)
XA0
XA1
Note:
1. The timing requirements shown in Figure 32-5 (i.e., tDVXH, tXHXL, and tXLDX) also apply to loading operation.
Figure 32-7. Parallel Programming Timing, Reading Sequence (within the Same Page) with Timing Requirements(1)
LOAD ADDRESS (LOW BYTE)
tXLOL
READ DATA (LOW BYTE)
READ DATA (HIGH BYTE)
LOAD ADDRESS (LOW BYTE)
XTAL1
tBVDV
BS1
tOLDV
OE
tOHDZ
DATA
ADDR0 (Low Byte)
DATA (Low Byte)
DATA (High Byte)
ADDR1 (Low Byte)
XA0
XA1
Note:
1. The timing requirements shown in Figure 32-5 (i.e., tDVXH, tXHXL, and tXLDX) also apply to reading operation.
Table 32-18. Parallel Programming Characteristics
Symbol VPP IPP tDVXH tXLXH tXHXL tXLDX Parameter Programming Enable Voltage (RESET input) Programming Enable Current Data and Control Valid before XTAL1 High XTAL1 Low to XTAL1 High XTAL1 Pulse Width High Data and Control Hold after XTAL1 Low 67 200 150 67 Min 11.5 Typ Max 12.5 250 Units V A ns ns ns ns
239
8042A-AVR-07/09
ATmega16HVB/32HVB
Table 32-18. Parallel Programming Characteristics (Continued)
Symbol tXLWL tXLPH tPLXH tBVPH tPHPL tPLBX tWLBX tPLWL tBVWL tWLWH tWLRL tWLRH tWLRH_CE tXLOL tBVDV tOLDV tOHDZ Notes: 1. Parameter XTAL1 Low to WR Low XTAL1 Low to PAGEL high PAGEL low to XTAL1 high BS1 Valid before PAGEL High PAGEL Pulse Width High BS1 Hold after PAGEL Low BS2/1 Hold after WR Low PAGEL Low to WR Low BS1 Valid to WR Low WR Pulse Width Low WR Low to RDY/BSY Low WR Low to RDY/BSY High
(1) (2)
Min 0 0 150 67 150
Typ
Max
Units
ns 67 67 67 67 150 0 3.7 7.5 0 0 250 ns OE Low to DATA Valid OE High to DATA Tri-stated 250 250 1 4.5 ms 9 s
WR Low to RDY/BSY High for Chip Erase XTAL1 Low to OE Low BS1 Valid to DATA valid
tWLRH is valid for the Write Flash, Write EEPROM, Write Fuse bits and Write Lock bits commands. 2. tWLRH_CE is valid for the Chip Erase command
240
8042A-AVR-07/09
ATmega16HVB/32HVB
33. Typical Characteristics
All Typical Characteristics contained in this data sheet are based on characterization of ATmega16/32HVB.
33.1
33.1.1
Supply Current Characteristics
Active supply current characteristics Active mode current measurements with all bits in the PRR registers set and all I/O modules turned off. Figure 33-1. Active Supply Current vs. VVFET, Internal RC Oscillator, 8 MHz.
4 3.95 3.9 I VFET [mA] 3.85 3.8 3.75 3.7 3.65 3.6 4 6 8 10 12 VVFET [V] 14 16 18 20
85 C
25 C
-40 C
Figure 33-2. Active Supply Current vs. VVFET, Internal RC Oscillator, 4 MHz.
2.44
2.4
2.36 I VFET [mA]
85 C
2.32
25 C
2.28
2.24
-40 C
2.2 4 6 8 10 12 VVFET [V] 14 16 18 20
241
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 33-3. Active Supply Current vs. VVFET, Internal RC Oscillator, 2 MHz.
1.33
1.31
1.29 I VFET [mA]
85 C
1.27
25 C
1.25
1.23
-40 C
4 6 8 10 12 VVFET [V] 14 16 18 20
1.21
Figure 33-4. Active Supply Current vs. VVFET, Internal RC Oscillator, 1 MHz.
0.8 0.79 0.78
I VFET [mA]
85 C 25 C
0.77 0.76 0.75 0.74
-40 C
0.73 0.72 4 6 8 10 12 VVFET [V] 14 16 18 20
242
8042A-AVR-07/09
ATmega16HVB/32HVB
33.1.2 Idle supply current characteristics Idle current consumption measurements with all bits in the PRR registers set and all I/O modules are turned off. Figure 33-5. Idle Supply Current vs. VVFET, Internal RC Oscillator, 8 MHz.
0.815 0.795
85 C
0.775 I VFET [mA] 0.755 0.735 0.715 0.695 0.675 4 6 8 10 12 VVFET [V] 14 16 18 20
25 C
-40 C
Figure 33-6. Idle Supply Current vs. VVFET, Internal RC Oscillator, 4 MHz.
0.48
0.47
85 C
0.46 I VFET [mA]
0.45
25 C
0.44
0.43
-40 C
0.42 4 6 8 10 12 VVFET [V] 14 16 18 20
243
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 33-7. Idle Supply Current vs. VVFET, Internal RC Oscillator, 2 MHz.
0.308
85 C
0.304 0.3 I VFET [mA] 0.296 0.292 0.288 0.284 0.28 4 6 8 10 12 VVFET [V] 14 16 18 20
25 C
-40 C
Figure 33-8. Idle Supply Current vs. VVFET, Internal RC Oscillator, 1 MHz.
0.225
85 C
0.221
I VFET [mA]
0.217
25 C
0.213
-40 C
0.209
0.205 4 6 8 10 12 VVFET [V] 14 16 18 20
244
8042A-AVR-07/09
ATmega16HVB/32HVB
33.1.3 Power-save current characteristics Power-save current consumption with External Interrupt and SMBus connect/disconnect functionality enabled. The Watchdog Timer, CC-ADC, Current Battery Protection (CBP), VREF, and OC/OD are disabled. Figure 33-9. Power-Save Supply Current vs. VVFET, External Interrupt and SMBus enabled, all other modules disabled.
35 33 31 29
I VFET [uA]
85 C 25 C -40 C
27 25 23 21 19 17 4 6 8 10 12 VVFET [V] 14 16 18 20
Table 33-1 shows additional current consumption that needs to be added to the total power-budget when additional modules are enableds. Table 33-1. Typical additional I/O modules current consumption in Power-save
I/O modules enabled WDT X X X X Note: X X X X X X X X VREF CBP
(1)
Typical current consumption
(2)
CC/OD
CC-ADC
(TA=25C and VVFET=12V) 0.8 A 12 A 41 A 55 A
1. Default I/O register configuration used. PPI and NNI connected to GND. 2. Measurements done with Fairchild FDS6690A N-Channel MOSFET.
245
8042A-AVR-07/09
ATmega16HVB/32HVB
33.1.4 Power-off current characteristics Figure 33-10. Power-Off Supply Current vs. VVFET
1.8
85 C 25 C -40 C
1.6
1.4 I VFET [uA]
1.2
1
0.8
0.6 4 6 8 10 12 VVFET [V] 14 16 18 20
33.2
33.2.1
NFET Driver Characteristics
OC/OD Levels Figure 33-11. OC/OD pin voltage vs. VVFET
35
30
Pin Voltage [V]
-40 C 25 C 85 C
25
20
15
10 6 8 10 12 VVFET [V] 14 16 18
246
8042A-AVR-07/09
ATmega16HVB/32HVB
33.2.2 OC/OD rise time from 0V to 2V gate-source voltage with 4.7nF load Figure 33-12. OC/OD Rise time, VGS = 0 to 2V vs. VVFET
5 4.5 4 3.5 Time [ms] 3 2.5 2 1.5 1 0.5 0 6 8 10 12 VVFET [V] 14 16 18
70 C 25 C
33.2.3
OC/OD rise time from 2V to 4V gate-source voltage with 4.7nF load Figure 33-13. OC/OD Rise time, VGS = 2 to 4V vs. VVFET
3
2.5
2 Time [ms]
1.5
70 C 25 C
1
0.5
0
6
8
10
12 VVFET [V]
14
16
18
247
8042A-AVR-07/09
ATmega16HVB/32HVB
33.3 Battery Protection Characteristics
Figure 33-14. Battery Protection Level
Max
310
Detection Level [mV]
TYP(25 C) Min
260 210 160 110 60 10
F3 F4 F5 F6 F7 F8 F9 FA FB FC FD 77 78 79 7A 7B 7C 7D 37 38 39 3A 3B 3C 3D 17
Register Value
33.4
33.4.1
Clock Characteristics
Fast RC Oscillator characteristics Figure 33-15. Fast RC Oscillator Frequency vs. Temperature (After factory calibration)
8.1 8.05 8
Frequency [MHz]
7.95 7.9 7.85 7.8 7.75 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 Temperature [C]
248
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 33-16. Calibrated Fast RC Oscillator Frequency vs. OSCCAL value.
16
25 C
14
12
F RC (M Hz)
10
8
6
4 0 16 32 48 64 80 96 112 128 144 160 176 192 208 224 240 256 OSCCAL VALUE
33.4.2
Ultra Low Power RC Oscillator characteristics Figure 33-17. ULP RC Oscillator Frequency vs. Temperature
113 112 111 Frequency [kHz] 110 109 108 107 106 105 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 Temperature [C]
249
8042A-AVR-07/09
ATmega16HVB/32HVB
33.4.3 Slow RC Oscillator characteristics Figure 33-18. Slow RC Oscillator Frequency vs. Temperature
118.6 118.5 118.4 118.3 Frequency [kHz] 118.2 118.1 118 117.9 117.8 117.7 117.6 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 Temperature [C]
33.5
Voltage Reference characteristics
Figure 33-19. Typical VREF curve with Atmel factory calibration at 25C and 85C.
1.101 1.100 1.099 1.098
VREF [V]
1.097 1.096 1.095 1.094 1.093 1.092 1.091 -40 -20 0 20 40 60 80
Temperature [C]
250
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 33-20. Typical VREF deviation curve with Atmel factory calibration at 25C and 85C.
33.6
Voltage Regulator characteristics
Figure 33-21. Voltage Regulator vs. VVFET, ILOAD = 10 mA.
3.27
-40 C 25 C 85 C
3.26
3.25 VREG [V]
3.24
3.23
3.22
3.21 4 6 8 10 12 14 16 18 20 22 24 26 VVFET [V]
251
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 33-22. Voltage Regulator vs. VVFET, ILOAD = 20 mA.
3.3 3.2 3.1 3 VREG [V] 2.9 2.8 2.7 2.6 2.5 2.4 4 6 8 10 12 14 16 18 20 22 24 26 VVFET [V]
-40 C 25 C 85 C
Figure 33-23. Voltage Regulator Short-circuit Level at VVFET pin vs. Temperature.
3.75
3.7
Rising
3.65 VRSCL [V]
3.6
3.55
Falling
3.5
3.45 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 Temperature [C]
252
8042A-AVR-07/09
ATmega16HVB/32HVB
Figure 33-24. BLOD Level.
2.661 2.659 2.657 2.655 2.653 VBLOD [V] 2.651 2.649 2.647 2.645 2.643 2.641 2.639 2.637 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 Temperature [C]
33.7
BOD Threshold characteristics
Figure 33-25. BOD Level.
3 2.98 2.96 2.94 VCC [V] 2.92 2.9 2.88 2.86 2.84 2.82 -40 -30 -20 -10 0 10 20 30 40 50 60 70 80 90 Temperature [C]
Rising
Falling
253
8042A-AVR-07/09
ATmega16HVB/32HVB
34. Register Summary
Address
(0xFF) (0xFE) (0xFD) (0xFC) (0xFB) (0xFA) (0xF9) (0xF8) (0xF7) (0xF6) (0xF5) (0xF4) (0xF3) (0xF2) (0xF1) (0xF0) (0xEF) (0xEE) (0xED) (0xEC) (0xEB) (0xEA) (0xE9) (0xE8) (0xE7) (0xE6) (0xE5) (0xE4) (0xE3) (0xE2) (0xE1) (0xE0) (0xDF) (0xDE) (0xDD) (0xDC) (0xDB) (0xDA) (0xD9) (0xD8) (0xD7) (0xD6) (0xD5) (0xD4) (0xD3) (0xD2) (0xD1) (0xD0) (0xCF) (0xCE) (0xCD) (0xCC) (0xCB) (0xCA) (0xC9) (0xC8) (0xC7) (0xC6) (0xC5) (0xC4) (0xC3) (0xC2) (0xC1) (0xC0)
Name
Reserved BPPLR BPCR BPHCTR BPOCTR BPSCTR BPCHCD BPDHCD BPCOCD BPDOCD BPSCD Reserved BPIFR BPIMSK CBCR FCSR Reserved Reserved Reserved Reserved Reserved CADRDC CADRCC CADCSRC CADCSRB CADCSRA CADICH CADICL CADAC3 CADAC2 CADAC1 CADAC0 Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved CHGDCSR Reserved BGCSR BGCRR BGCCR Reserved Reserved Reserved Reserved Reserved Reserved Reserved ROCR Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved
Bit 7
- - - - - -
Bit 6
- - - - -
Bit 5
- - EPID
Bit 4
- - SCD
Bit 3
- - DOCD
Bit 2
- - COCD HCPT[5:0] OCPT[5:0]
Bit 1
- BPPLE DHCD
Bit 0
- BPPL CHCD
Page
140 141 143 142 142 145 145 145 144 144
SCPT[6:0] CHCDL[7:0] DHCDL[7:0] COCDL[7:0] DOCDL[7:0] SCDL[7:0]
- - - - - - - - - -
- - - - - - - - - -
- - - - - - - - - -
- SCIF SCIE - - - - - - - CADRDC[7:0] CADRCC[7:0]
- DOCIF DOCIE CBE4 DUVRD - - - - -
- COCIF COCIE CBE3 CPS - - - - -
- DHCIF DHCIE CBE2 DFE - - - - -
- CHCIF CHCIE CBE1 CFE - - - - - 115 115 147 146 155 153
- CADEN
CADACIE CADPOL
CADRCIE CADUB
CADICIE CADAS[1:0] CADIC[15:8] CADIC[7:0]
-
CADACIF CADSI[1:0]
CADRCIF
CADVSE CADICIF CADSE
114 112 111 114 114 114 114 114 114
CADAC[31:24] CADAC[23:16] CADAC[15:8] CADAC[7:0] - - - - - - - - - - - - - - - - - - - - - - ROCS - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ROCD - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - BGD - - - - - - - - - - - BATTPVL - BGSCDE BGCR[7:0] BGCC[5:0] - - - - - - - - - - - - - - - - - - - - - - - ROCWIF - - - - - - - - - - - - - - - ROCWIE - - - - - - - - - - - - - - - - - - - CHGDISC1 - - - - - - - - - - - - - CHGDISC1 - - - - - - - - - - - - - CHGDIF - BGSCDIF - - - - - - - - - - - CHGDIE - BGSCDIE
131 127 126 254
134
254
8042A-AVR-07/09
ATmega16HVB/32HVB
Address
(0xBF) (0xBE) (0xBD) (0xBC) (0xBB) (0xBA) (0xB9) (0xB8) (0xB7) (0xB6) (0xB5) (0xB4) (0xB3) (0xB2) (0xB1) (0xB0) (0xAF) (0xAE) (0xAD) (0xAC) (0xAB) (0xAA) (0xA9) (0xA8) (0xA7) (0xA6) (0xA5) (0xA4) (0xA3) (0xA2) (0xA1) (0xA0) (0x9F) (0x9E) (0x9D) (0x9C) (0x9B) (0x9A) (0x99) (0x98) (0x97) (0x96) (0x95) (0x94) (0x93) (0x92) (0x91) (0x90) (0x8F) (0x8E) (0x8D) (0x8C) (0x8B) (0x8A) (0x89) (0x88) (0x87) (0x86) (0x85) (0x84) (0x83) (0x82) (0x81) (0x80) (0x7F) (0x7E)
Name
Reserved TWBCSR TWAMR TWCR TWDR TWAR TWSR TWBR Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved OCR1B OCR1A Reserved Reserved TCNT1H TCNT1L Reserved Reserved TCCR1B TCCR1A Reserved DIDR0
Bit 7
- TWBCIF TWINT
Bit 6
- TWBCIE TWEA
Bit 5
- - TWSTA
Bit 4
- - TWAM[6:0] TWSTO TWA[6:0]
Bit 3
- - TWWC
Bit 2
- TWBDT1 TWEN
Bit 1
- TWBDT0 -
Bit 0
- TWBCIP - TWIE TWGCE
Page
187 187 184 186 186 185 184
2-wire Serial Interface Data Register TWS[7:3] 2-wire Serial Interface Bit Rate Register - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - TWPS1 TWPS0
Timer/Counter1 - Output Compare Register B Timer/Counter1 - Output Compare Register A - - - - - - - - - - - - - - - -
95 95
Timer/Counter1 (8 Bit) High Byte Timer/Counter1 (8 Bit) Low Byte - - - TCW1 - - - - - ICEN1 - - - - - ICNC1 - - - - - ICES1 - - - - - ICS1 - - - - CS12 - - - - - CS11 - - PA1DID - - CS10 WGM10 - PA0DID
95 95
81 94 122
255
8042A-AVR-07/09
ATmega16HVB/32HVB
Address
(0x7D) (0x7C) (0x7B) (0x7A) (0x79) (0x78) (0x77) (0x76) (0x75) (0x74) (0x73) (0x72) (0x71) (0x70) (0x6F) (0x6E) (0x6D) (0x6C) (0x6B) (0x6A) (0x69) (0x68) (0x67) (0x66) (0x65) (0x64) (0x63) (0x62) (0x61) (0x60) 0x3F (0x5F) 0x3E (0x5E) 0x3D (0x5D) 0x3C (0x5C) 0x3B (0x5B) 0x3A (0x5A) 0x39 (0x59) 0x38 (0x58) 0x37 (0x57) 0x36 (0x56) 0x35 (0x55) 0x34 (0x54) 0x33 (0x53) 0x32 (0x52) 0x31 (0x51) 0x30 (0x50) 0x2F (0x4F) 0x2E (0x4E) 0x2D (0x4D) 0x2C (0x4C) 0x2B (0x4B) 0x2A (0x4A) 0x29 (0x49) 0x28 (0x48) 0x27 (0x47) 0x26 (0x46) 0x25 (0x45) 0x24 (0x44) 0x23 (0x43) 0x22 (0x42) 0x21 (0x41) 0x20 (0x40) 0x1F (0x3F) 0x1E (0x3E) 0x1D (0x3D) 0x1C (0x3C)
Name
Reserved VADMUX Reserved VADCSR VADCH VADCL Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved TIMSK1 TIMSK0 Reserved PCMSK1 PCMSK0 Reserved EICRA PCICR Reserved FOSCCAL Reserved PRR0 Reserved Reserved CLKPR WDTCSR SREG SPH SPL Reserved Reserved Reserved Reserved Reserved SPMCSR Reserved MCUCR MCUSR SMCR Reserved DWDR Reserved Reserved SPDR SPSR SPCR GPIOR2 GPIOR1 OCR0B OCR0A TCNT0H TCNT0L TCCR0B TCCR0A GTCCR EEARH EEARL EEDR EECR GPIOR0 EIMSK EIFR
Bit 7
- - - - - - - - - - - - - - - - - - ISC31 - - - - - - CLKPCE WDIF I SP15 SP7 - - - - - SPMIE - - - - - - - SPIF SPIE
Bit 6
- - - - - - - - - - - - - - - - - - ISC30 - - - PRTWI - - - WDIE T SP14 SP6 - - - - - RWWSB - - - - - - - WCOL SPE
Bit 5
- - - - - - - - - - - - - - - - - - ISC21 - - - PRVRM - - - WDP3 H SP13 SP5 - - - - - SIGRD - CKOE - - - - - - DORD
Bit 4
- - - - -
Bit 3
- - VADEN
Bit 2
-
Bit 1
-
Bit 0
-
Page
120
VADMUX[3:0] - VADSC - VADCCIF - VADCCIE
120 121 121
VADC Data Register High byte - - - - - - - - ICIE1 ICIE0 - PCINT[15:8] - - - - - - - - OCIE1B OCIE0B - PCINT[3:0] - ISC11 - - - PRSPI - - - WDE V SP11 SP3 - - - - - RFLB - - WDRF - - - - CPOL - ISC10 - - - PRTIM1 - - - WDP2 N SP10 SP2 - - - - - PGWRT - - BODRF SM[2:0] - - - - CPHA - - - - SPR1 - ISC01 PCIE1 - - PRTIM0 - - CLKPS1 WDP1 Z SP9 SP1 - - - - - PGERS - IVSEL EXTRF - ISC00 PCIE0 - - - - - - - - - OCIE1A OCIE0A - - - - - - - - - TOIE1 TOIE0 -
VADC Data Register Low byte - - - - - - - - - - - - - ISC20 - - - - - - - WDCE S SP12 SP4 - - - - - CTPB - PUD OCDRF - - - - - MSTR debugWIRE Data Register - -
96 96 60 61 58 60 32
Fast Oscillator Calibration Register - PRVADC - - CLKPS0 WDP0 C SP8 SP0 - - - - - SPMEN - IVCE PORF SE -
40
32 49 10 13 13
206 78/32 49 39 190
SPI Data Register SPI2X SPR0
107 106 105 24 24 95 95 95 95 CS02 - - - CS01 - - CS00 WGM00 PSRSYNC 20 20 20 EEMPE INT2 INTF2 EEPE INT1 INTF1 EERE INT0 INTF0 21 24 59 59 81 94
General Purpose I/O Register 2 General Purpose I/O Register 1 Timer/Counter0 Output Compare Register B Timer/Counter0 Output Compare Register A Timer/Counter0 (8 Bit) High Byte Timer/Counter0 (8 Bit) Low Byte - TCW0 TSM - - ICEN0 - - - ICNC0 - - - ICES0 - - - ICS0 - -
EEPROM High byte
EEPROM Address Register Low Byte EEPROM Data Register - - - - - - EEPM1 - - EEPM0 - - EERIE INT3 INTF3 General Purpose I/O Register 0
256
8042A-AVR-07/09
ATmega16HVB/32HVB
Address
0x1B (0x3B) 0x1A (0x3A) 0x19 (0x39) 0x18 (0x38) 0x17 (0x37) 0x16 (0x36) 0x15 (0x35) 0x14 (0x34) 0x13 (0x33) 0x12 (0x32) 0x11 (0x31) 0x10 (0x30) 0x0F (0x2F) 0x0E (0x2E) 0x0D (0x2D) 0x0C (0x2C) 0x0B (0x2B) 0x0A (0x2A) 0x09 (0x29) 0x08 (0x28) 0x07 (0x27) 0x06 (0x26) 0x05 (0x25) 0x04 (0x24) 0x03 (0x23) 0x02 (0x22) 0x01 (0x21) 0x00 (0x20)
Name
PCIFR Reserved Reserved Reserved OSICSR TIFR1 TIFR0 Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved Reserved PORTC Reserved PINC PORTB DDRB PINB PORTA DDRA PINA
Bit 7
- - - - - - - - - - - - - - - - - - - - - - PORTB7 DDB7 PINB7 - - -
Bit 6
- - - - - - - - - - - - - - - - - - - - - - PORTB6 DDB6 PINB6 - - -
Bit 5
- - - - - - - - - - - - - - - - - - - PORTC5 - - PORTB5 DDB5 PINB5 - - -
Bit 4
- - - - OSISEL0 - - - - - - - - - - - - - - PORTC4 - PINC4 PORTB4 DDB4 PINB4 - - -
Bit 3
- - - - - ICF1 ICF0 - - - - - - - - - - - - PORTC3 - PINC3 PORTB3 DDB3 PINB3 PORTA3 DDA3 PINA3
Bit 2
- - - - - OCF1B OCF0B - - - - - - - - - - - - PORTC2 - PINC2 PORTB2 DDB2 PINB2 PORTA2 DDA2 PINA2
Bit 1
PCIF1 - - - OSIST OCF1A OCF0A - - - - - - - - - - - - PORTC1 - PINC1 PORTB1 DDB1 PINB1 PORTA1 DDA1 PINA1
Bit 0
PCIF0 - - - OSIEN TOV1 TOV0 - - - - - - - - - - - - PORTC0 - PINC0 PORTB0 DDB0 PINB0 PORTA0 DDA0 PINA0
Page
60
33 96 96
66 66 78 78 78 78 78 78
Notes:
1. For compatibility with future devices, reserved bits should be written to zero if accessed. Reserved I/O memory addresses should never be written. 2. I/O registers within the address range $00 - $1F are directly bit-accessible using the SBI and CBI instructions. In these registers, the value of single bits can be checked by using the SBIS and SBIC instructions. 3. Some of the status flags are cleared by writing a logical one to them. Note that the CBI and SBI instructions will operate on all bits in the I/O register, writing a one back into any flag read as set, thus clearing the flag. The CBI and SBI instructions work with registers 0x00 to 0x1F only. 4. When using the I/O specific commands IN and OUT, the I/O addresses $00 - $3F must be used. When addressing I/O registers as data space using LD and ST instructions, $20 must be added to these addresses. The ATmega16HVB/32HVB is a complex microcontroller with more peripheral units than can be supported within the 64 location reserved in Opcode for the IN and OUT instructions. For the Extended I/O space from $60 - $FF in SRAM, only the ST/STS/STD and LD/LDS/LDD instructions can be used.
257
8042A-AVR-07/09
ATmega16HVB/32HVB
35. Instruction Set Summary
Mnemonics
ADD ADC ADIW SUB SUBI SBC SBCI SBIW AND ANDI OR ORI EOR COM NEG SBR CBR INC DEC TST CLR SER MUL MULS MULSU FMUL FMULS FMULSU RJMP IJMP JMP RCALL ICALL CALL RET RETI CPSE CP CPC CPI SBRC SBRS SBIC SBIS BRBS BRBC BREQ BRNE BRCS BRCC BRSH BRLO BRMI BRPL BRGE BRLT BRHS BRHC BRTS BRTC BRVS BRVC Rd,Rr Rd,Rr Rd,Rr Rd,K Rr, b Rr, b P, b P, b s, k s, k k k k k k k k k k k k k k k k k k k k
Operands
Rd, Rr Rd, Rr Rdl,K Rd, Rr Rd, K Rd, Rr Rd, K Rdl,K Rd, Rr Rd, K Rd, Rr Rd, K Rd, Rr Rd Rd Rd,K Rd,K Rd Rd Rd Rd Rd Rd, Rr Rd, Rr Rd, Rr Rd, Rr Rd, Rr Rd, Rr k Add two Registers
Description
Rd Rd + Rr
Operation
Flags
Z,C,N,V,H Z,C,N,V,H Z,C,N,V,S Z,C,N,V,H Z,C,N,V,H Z,C,N,V,H Z,C,N,V,H Z,C,N,V,S Z,N,V Z,N,V Z,N,V Z,N,V Z,N,V Z,C,N,V Z,C,N,V,H Z,N,V Z,N,V Z,N,V Z,N,V Z,N,V Z,N,V None Z,C Z,C Z,C Z,C Z,C Z,C None None None None None None None I None Z, N,V,C,H Z, N,V,C,H Z, N,V,C,H None None None None None None None None None None None None None None None None None None None None None None
#Clocks
1 1 2 1 1 1 1 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 3 3 3 4 4 4 1/2/3 1 1 1 1/2/3 1/2/3 1/2/3 1/2/3 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2 1/2
ARITHMETIC AND LOGIC INSTRUCTIONS Add with Carry two Registers Add Immediate to Word Subtract two Registers Subtract Constant from Register Subtract with Carry two Registers Subtract with Carry Constant from Reg. Subtract Immediate from Word Logical AND Registers Logical AND Register and Constant Logical OR Registers Logical OR Register and Constant Exclusive OR Registers One's Complement Two's Complement Set Bit(s) in Register Clear Bit(s) in Register Increment Decrement Test for Zero or Minus Clear Register Set Register Multiply Unsigned Multiply Signed Multiply Signed with Unsigned Fractional Multiply Unsigned Fractional Multiply Signed Fractional Multiply Signed with Unsigned Relative Jump Indirect Jump to (Z) Direct Jump Relative Subroutine Call Indirect Call to (Z) Direct Subroutine Call Subroutine Return Interrupt Return Compare, Skip if Equal Compare Compare with Carry Compare Register with Immediate Skip if Bit in Register Cleared Skip if Bit in Register is Set Skip if Bit in I/O Register Cleared Skip if Bit in I/O Register is Set Branch if Status Flag Set Branch if Status Flag Cleared Branch if Equal Branch if Not Equal Branch if Carry Set Branch if Carry Cleared Branch if Same or Higher Branch if Lower Branch if Minus Branch if Plus Branch if Greater or Equal, Signed Branch if Less Than Zero, Signed Branch if Half Carry Flag Set Branch if Half Carry Flag Cleared Branch if T Flag Set Branch if T Flag Cleared Branch if Overflow Flag is Set Branch if Overflow Flag is Cleared Rd Rd + Rr + C Rdh:Rdl Rdh:Rdl + K Rd Rd - Rr Rd Rd - K Rd Rd - Rr - C Rd Rd - K - C Rdh:Rdl Rdh:Rdl - K Rd Rd * Rr Rd Rd * K Rd Rd v Rr Rd Rd v K Rd Rd Rr Rd 0xFF - Rd Rd 0x00 - Rd Rd Rd v K Rd Rd * (0xFF - K) Rd Rd + 1 Rd Rd - 1 Rd Rd * Rd Rd Rd Rd Rd 0xFF R1:R0 Rd x Rr R1:R0 Rd x Rr R1:R0 Rd x Rr
1 R1:R0 (Rd x Rr) << 1 R1:R0 (Rd x Rr) << 1
PC PC + k + 1 PC Z PC k PC PC + k + 1 PC Z PC k PC STACK PC STACK if (Rd = Rr) PC PC + 2 or 3 Rd - Rr Rd - Rr - C Rd - K if (Rr(b)=0) PC PC + 2 or 3 if (Rr(b)=1) PC PC + 2 or 3 if (P(b)=0) PC PC + 2 or 3 if (P(b)=1) PC PC + 2 or 3 if (SREG(s) = 1) then PCPC+k + 1 if (SREG(s) = 0) then PCPC+k + 1 if (Z = 1) then PC PC + k + 1 if (Z = 0) then PC PC + k + 1 if (C = 1) then PC PC + k + 1 if (C = 0) then PC PC + k + 1 if (C = 0) then PC PC + k + 1 if (C = 1) then PC PC + k + 1 if (N = 1) then PC PC + k + 1 if (N = 0) then PC PC + k + 1 if (N V= 0) then PC PC + k + 1 if (N V= 1) then PC PC + k + 1 if (H = 1) then PC PC + k + 1 if (H = 0) then PC PC + k + 1 if (T = 1) then PC PC + k + 1 if (T = 0) then PC PC + k + 1 if (V = 1) then PC PC + k + 1 if (V = 0) then PC PC + k + 1
R1:R0 (Rd x Rr) <<
BRANCH INSTRUCTIONS
258
8042A-AVR-07/09
ATmega16HVB/32HVB
35. Instruction Set Summary (Continued)
Mnemonics
BRIE BRID SBI CBI LSL LSR ROL ROR ASR SWAP BSET BCLR BST BLD SEC CLC SEN CLN SEZ CLZ SEI CLI SES CLS SEV CLV SET CLT SEH CLH DATA TRANSFER INSTRUCTIONS MOV MOVW LDI LD LD LD LD LD LD LDD LD LD LD LDD LDS ST ST ST ST ST ST STD ST ST ST STD STS LPM LPM LPM SPM IN Rd, P Rd, Z Rd, Z+ Rd, Rr Rd, Rr Rd, K Rd, X Rd, X+ Rd, - X Rd, Y Rd, Y+ Rd, - Y Rd,Y+q Rd, Z Rd, Z+ Rd, -Z Rd, Z+q Rd, k X, Rr X+, Rr - X, Rr Y, Rr Y+, Rr - Y, Rr Y+q,Rr Z, Rr Z+, Rr -Z, Rr Z+q,Rr k, Rr Move Between Registers Copy Register Word Load Immediate Load Indirect Load Indirect and Post-Inc. Load Indirect and Pre-Dec. Load Indirect Load Indirect and Post-Inc. Load Indirect and Pre-Dec. Load Indirect with Displacement Load Indirect Load Indirect and Post-Inc. Load Indirect and Pre-Dec. Load Indirect with Displacement Load Direct from SRAM Store Indirect Store Indirect and Post-Inc. Store Indirect and Pre-Dec. Store Indirect Store Indirect and Post-Inc. Store Indirect and Pre-Dec. Store Indirect with Displacement Store Indirect Store Indirect and Post-Inc. Store Indirect and Pre-Dec. Store Indirect with Displacement Store Direct to SRAM Load Program Memory Load Program Memory Load Program Memory and Post-Inc Store Program Memory In Port Rd Rr Rd+1:Rd Rr+1:Rr Rd K Rd (X) Rd (X), X X + 1 X X - 1, Rd (X) Rd (Y) Rd (Y), Y Y + 1 Y Y - 1, Rd (Y) Rd (Y + q) Rd (Z) Rd (Z), Z Z+1 Z Z - 1, Rd (Z) Rd (Z + q) Rd (k) (X) Rr (X) Rr, X X + 1 X X - 1, (X) Rr (Y) Rr (Y) Rr, Y Y + 1 Y Y - 1, (Y) Rr (Y + q) Rr (Z) Rr (Z) Rr, Z Z + 1 Z Z - 1, (Z) Rr (Z + q) Rr (k) Rr R0 (Z) Rd (Z) Rd (Z), Z Z+1 (Z) R1:R0 Rd P None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None None 1 1 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 3 3 3 1 k k P,b P,b Rd Rd Rd Rd Rd Rd s s Rr, b Rd, b
Operands
Description
Branch if Interrupt Enabled Branch if Interrupt Disabled Set Bit in I/O Register Clear Bit in I/O Register Logical Shift Left Logical Shift Right Rotate Left Through Carry Rotate Right Through Carry Arithmetic Shift Right Swap Nibbles Flag Set Flag Clear Bit Store from Register to T Bit load from T to Register Set Carry Clear Carry Set Negative Flag Clear Negative Flag Set Zero Flag Clear Zero Flag Global Interrupt Enable Global Interrupt Disable Set Signed Test Flag Clear Signed Test Flag Set Twos Complement Overflow. Clear Twos Complement Overflow Set T in SREG Clear T in SREG Set Half Carry Flag in SREG Clear Half Carry Flag in SREG
Operation
if ( I = 1) then PC PC + k + 1 if ( I = 0) then PC PC + k + 1 I/O(P,b) 1 I/O(P,b) 0 Rd(n+1) Rd(n), Rd(0) 0 Rd(n) Rd(n+1), Rd(7) 0 Rd(0)C,Rd(n+1) Rd(n),CRd(7) Rd(7)C,Rd(n) Rd(n+1),CRd(0) Rd(n) Rd(n+1), n=0..6 Rd(3..0)Rd(7..4),Rd(7..4)Rd(3..0) SREG(s) 1 SREG(s) 0 T Rr(b) Rd(b) T C1 C0 N1 N0 Z1 Z0 I1 I0 S1 S0 V1 V0 T1 T0 H1 H0
Flags
None None None None Z,C,N,V Z,C,N,V Z,C,N,V Z,C,N,V Z,C,N,V None SREG(s) SREG(s) T None C C N N Z Z I I S S V V T T H H
#Clocks
1/2 1/2 2 2 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
BIT AND BIT-TEST INSTRUCTIONS
259
8042A-AVR-07/09
ATmega16HVB/32HVB
35. Instruction Set Summary (Continued)
Mnemonics
OUT PUSH POP NOP SLEEP WDR BREAK
Operands
P, Rr Rr Rd Out Port Push Register on Stack
Description
P Rr STACK Rr Rd STACK
Operation
Flags
None None None None
#Clocks
1 2 2 1 1 1 N/A
Pop Register from Stack No Operation Sleep Watchdog Reset Break
MCU CONTROL INSTRUCTIONS (see specific descr. for Sleep function) (see specific descr. for WDR/timer) For On-chip Debug Only None None None
260
8042A-AVR-07/09
ATmega16HVB/32HVB
36. Ordering Information
36.1 ATmega16HVB
Power Supply 4 - 25V Ordering Code ATMEGA16HVB-8X3 Package 44X1 Operation Range -40C to 85C
Speed (MHz) 1 - 8 MHz
Package Type 44X1 44-lead, 4.4 mm Body Width, Plastic Thin Shrink Small Outline Package (TSSOP)
261
8042A-AVR-07/09
ATmega16HVB/32HVB
36.2 ATmega32HVB
Power Supply 4 - 25V Ordering Code ATMEGA32HVB-8X3 Package 44X1 Operation Range -40C to 85C
Speed (MHz) 1 - 8 MHz
Package Type 44X1 44-lead, 4.4 mm Body Width, Plastic Thin Shrink Small Outline Package (TSSOP)
262
8042A-AVR-07/09
ATmega16HVB/32HVB
37. Packaging Information
37.1 44X1
32 32
1 1
C C
E1 E1
E E
End View End View
L L
44 44
O O
Top View Top View
b b A A e e D D Side View Side View A1 A1
SYMBOL SYMBOL A A A1 A1 b b C C D D E1 E1 E E e e L L O
O
COMMON DIMENSIONS (Unit of Measure = mm) COMMON DIMENSIONS (Unit of Measure = mm) MIN MAX NOM MIN - - 0.05 0.05 0.17 0.17 0.09 0.09 10.90 10.90 4.30 4.30 6.20 6.20 0.50 0.50 0o 0o NOM - - - - - 11.00 11.00 4.40 4.40 6.40 6.40 0.50 TYP 0.50 TYP 0.60 0.60 - - MAX 1.20 1.20 0.15 0.15 0.27 0.27 0.20 0.20 11.10 11.10 4.50 4.50 6.60 6.60 0.70 0.70 8o 8o
NOTE NOTE
Note: These drawings are for general information only. Refer to JEDEC Drawing MO-153BE. Note: These drawings are for general information only. Refer to JEDEC Drawing MO-153BE.
R
R
2325 Orchard Parkway San Orchard 95131 2325Jose, CA Parkway San Jose, CA 95131
TITLE 44X1, 44-lead, 4.4 mm Body Width, Plastic Thin Shrink TITLE Small 44-lead, 4.4 mm Body Width, Plastic Thin Shrink 44X1, Outline Package (TSSOP) Small Outline Package (TSSOP)
5/16/07 5/16/07 DRAWING NO. REV. DRAWING NO. REV. 44X1 A
44X1
A
263
8042A-AVR-07/09
ATmega16HVB/32HVB
38. Errata
38.1
38.1.1
ATmega16HVB
Rev. B No known errata.
38.1.2
Rev. A Not sampled.
38.2
38.2.1
ATmega32HVB
Rev. B No known errata.
38.2.2
Rev. A Not sampled.
264
8042A-AVR-07/09
ATmega16HVB/32HVB
39. Revision history
39.1 Rev A 08/09
1.
Initial revision
265
8042A-AVR-07/09
ATmega16HVB/32HVB
Table of Contents
Features ..................................................................................................... 1 1 Pin Configurations ................................................................................... 2
1.1TSSOP ......................................................................................................................2 1.2Pin Descriptions .........................................................................................................2
2
Overview ................................................................................................... 5
2.1Comparison Between ATmega16HVB and ATmega32HVB .....................................7
3 4 5 6 7
Disclaimer ................................................................................................. 8 Resources ................................................................................................. 8 About Code Examples ............................................................................. 8 Data Retention .......................................................................................... 8 AVR CPU Core .......................................................................................... 9
7.1Overview ....................................................................................................................9 7.2ALU - Arithmetic Logic Unit .....................................................................................10 7.3Status Register ........................................................................................................10 7.4General Purpose Register File ................................................................................12 7.5Stack Pointer ...........................................................................................................13 7.6Instruction Execution Timing ...................................................................................14 7.7Reset and Interrupt Handling ...................................................................................14
8
AVR Memories ........................................................................................ 17
8.1Overview ..................................................................................................................17 8.2In-System Reprogrammable Flash Program Memory .............................................17 8.3SRAM Data Memory ................................................................................................17 8.4EEPROM Data Memory ..........................................................................................19 8.5I/O Memory ..............................................................................................................19 8.6Register Description ................................................................................................20
9
System Clock and Clock Options ......................................................... 25
9.1Clock Systems and their Distribution .......................................................................25 9.2Clock Sources .........................................................................................................26 9.3Clock Startup Sequence ..........................................................................................28 9.4Clock Output ............................................................................................................28 9.5System Clock Prescaler ..........................................................................................28
i
8042A-AVR-07/09
9.6VADC Clock Prescaler ............................................................................................29 9.7OSI - Oscillator Sampling Interface ........................................................................29 9.8Register Description ................................................................................................32
10 Power Management and Sleep Modes ................................................. 35
10.1Sleep Modes ..........................................................................................................35 10.2Idle Mode ...............................................................................................................37 10.3ADC Noise Reduction ............................................................................................37 10.4Power-save Mode ..................................................................................................37 10.5Power-off Mode .....................................................................................................38 10.6Power Reduction Register .....................................................................................38 10.7Minimizing Power Consumption ............................................................................38 10.8Register Description ..............................................................................................39
11 System Control and Reset .................................................................... 42
11.1Resetting the AVR .................................................................................................42 11.2Reset Sources .......................................................................................................42 11.3Reset and the Voltage Reference .........................................................................45 11.4Watchdog Timer ....................................................................................................46 11.5Register Description ..............................................................................................49
12 Interrupts ................................................................................................ 52
12.1Overview ................................................................................................................52 12.2Interrupt Vectors in ATmega16HVB/32HVB ..........................................................52 12.3Moving Interrupts Between Application and Boot Space .......................................56 12.4Register Description ..............................................................................................56
13 External Interrupts ................................................................................. 58
13.1Overview ................................................................................................................58 13.2Register Description ..............................................................................................58
14 High Voltage I/O Ports ........................................................................... 62
14.1Overview ................................................................................................................62 14.2High Voltage Ports as General Digital I/O .............................................................63 14.3Overview ................................................................................................................64 14.4Alternate Port Functions ........................................................................................64 14.5Register Description ..............................................................................................66
15 Low Voltage I/O-Ports ............................................................................ 67
15.1Overview ................................................................................................................67
ii
ATmega16HVB/32HVB
8042A-AVR-07/09
ATmega16HVB/32HVB
15.2Low Voltage Ports as General Digital I/O ..............................................................68 15.3Alternate Port Functions ........................................................................................72 15.4Register Description ..............................................................................................78
16 Timer/Counter0 and Timer/Counter1 Prescalers ................................ 79
16.1Overview ................................................................................................................79 16.2External Clock Source ...........................................................................................80 16.3Register Description ..............................................................................................81
17 Timer/Counter (T/C0,T/C1) ..................................................................... 82
17.1Features ................................................................................................................82 17.2Overview ................................................................................................................82 17.3Timer/Counter Clock Sources ...............................................................................83 17.4Counter Unit ..........................................................................................................83 17.5Modes of Operation ...............................................................................................84 17.6Input Capture Unit .................................................................................................86 17.7Output Compare Unit .............................................................................................88 17.8Timer/Counter Timing Diagrams ...........................................................................89 17.9Accessing Registers in 16-bit Mode ......................................................................90 17.10Register Description ............................................................................................94
18 SPI - Serial Peripheral Interface ........................................................... 98
18.1Features ................................................................................................................98 18.2Overview ................................................................................................................98 18.3SS Pin Functionality ............................................................................................103 18.4Data Modes .........................................................................................................103 18.5Register Description ............................................................................................105
19 Coulomb Counter - Dedicated Fuel Gauging Sigma-delta ADC ...... 108
19.1Features ..............................................................................................................108 19.2Overview ..............................................................................................................108 19.3Normal Operation ................................................................................................109 19.4Regular Current Detection Operation ..................................................................110 19.5Offset Canceling by Polarity Switching ................................................................110 19.6Configuration and Usage .....................................................................................111 19.7Register Description ............................................................................................111
20 Voltage ADC - 7-channel General Purpose 12-bit Sigma-Delta ADC 117
20.1Features ..............................................................................................................117
iii
8042A-AVR-07/09
20.2Overview ..............................................................................................................117 20.3Operation .............................................................................................................117 20.4Register Description ............................................................................................120
21 Voltage Reference and Temperature Sensor .................................... 123
21.1Features ..............................................................................................................123 21.2Overview ..............................................................................................................123 21.3Operation .............................................................................................................124 21.4Bandgap Calibration ............................................................................................124 21.5Bandgap Buffer Settling Time ..............................................................................125 21.6Register Description ............................................................................................126
22 Charger Detect ..................................................................................... 129
22.1Features ..............................................................................................................129 22.2Overview ..............................................................................................................129 22.3Operation .............................................................................................................130 22.4Register Description ............................................................................................131
23 Voltage Regulator ................................................................................ 132
23.1Features ..............................................................................................................132 23.2Overview ..............................................................................................................132 23.3Regulator Start-up ...............................................................................................133 23.4Battery Pack Short Detection ..............................................................................133 23.5Black-Out Detection .............................................................................................133 23.6Register Description ............................................................................................134
24 Battery Protection ................................................................................ 135
24.1Features ..............................................................................................................135 24.2Overview ..............................................................................................................135 24.3Operation .............................................................................................................136 24.4External Protection Input .....................................................................................137 24.5Optimizing Usage for Low Power Consumption ..................................................139 24.6Battery Protection CPU Interface ........................................................................140 24.7Register Description ............................................................................................140
25 FET Driver ............................................................................................. 148
25.1Features ..............................................................................................................148 25.2Overview ..............................................................................................................148 25.3Operation and Usage ..........................................................................................149
iv
ATmega16HVB/32HVB
8042A-AVR-07/09
ATmega16HVB/32HVB
25.4Register Description ............................................................................................153
26 Cell Balancing ...................................................................................... 154
26.1Overview ..............................................................................................................154 26.2Register Description ............................................................................................155
27 2-wire Serial Interface .......................................................................... 156
27.1Features ..............................................................................................................156 27.2Two-wire Serial Interface Bus Definition ..............................................................156 27.3Data Transfer and Frame Format ........................................................................157 27.4Multi-master Bus Systems, Arbitration and Synchronization ...............................160 27.5Overview of the TWI Module ...............................................................................162 27.6Using the TWI ......................................................................................................165 27.7Transmission Modes ...........................................................................................168 27.8Multi-master Systems and Arbitration ..................................................................181 27.9Bus Connect/Disconnect for Two-wire Serial Interface .......................................183 27.10Register Description ..........................................................................................184
28 debugWIRE On-chip Debug System .................................................. 189
28.1Features ..............................................................................................................189 28.2Overview ..............................................................................................................189 28.3Physical Interface ................................................................................................189 28.4Software Break Points .........................................................................................190 28.5Limitations of debugWIRE ...................................................................................190 28.6Register Description ............................................................................................190
29 Boot Loader Support - Read-While-Write Self-Programming ......... 191
29.1Features ..............................................................................................................191 29.2Overview ..............................................................................................................191 29.3Application and Boot Loader Flash Sections .......................................................191 29.4Read-While-Write and No Read-While-Write Flash Sections ..............................192 29.5Boot Loader Lock Bits .........................................................................................194 29.6Entering the Boot Loader Program ......................................................................195 29.7Addressing the Flash During Self-Programming .................................................196 29.8Self-Programming the Flash ................................................................................197 29.9Register Description ............................................................................................206
30 Memory Programming ......................................................................... 208
30.1Program And Data Memory Lock Bits .................................................................208
v
8042A-AVR-07/09
30.2Fuse Bits ..............................................................................................................209 30.3Signature Bytes ...................................................................................................210 30.4Calibration Bytes .................................................................................................211 30.5Page Size ............................................................................................................211 30.6Serial Programming .............................................................................................211 30.7Parallel Programming ..........................................................................................216
31 Operating Circuit .................................................................................. 225 32 Electrical Characteristics .................................................................... 228
32.1Absolute Maximum Ratings* ...............................................................................228 32.2Supply Current Characteristics ............................................................................228 32.3NFET Driver Characteristics ................................................................................229 32.4Reset Characteristics ..........................................................................................230 32.5Voltage Regulator Characteristics .......................................................................230 32.6Voltage reference and Temperature Sensor Characteristics ..............................230 32.7ADC Characteristics ............................................................................................231 32.8Clock Characteristics ...........................................................................................232 32.9Cell Balancing Characteristic ...............................................................................233 32.10Battery Protection Characteristics .....................................................................233 32.11External Interrupt Characteristics ......................................................................233 32.12General I/O Lines Characteristics ......................................................................234 32.132-wire Serial Interface Characteristics ...............................................................235 32.14SPI Timing Characteristics ................................................................................236 32.15Serial Programming Characteristics ..................................................................237 32.16Parallel Programming Characteristics ...............................................................238
33 Typical Characteristics ........................................................................ 241
33.1Supply Current Characteristics ............................................................................241 33.2NFET Driver Characteristics ................................................................................246 33.3Battery Protection Characteristics .......................................................................248 33.4Clock Characteristics ...........................................................................................248 33.5Voltage Reference characteristics .......................................................................250 33.6Voltage Regulator characteristics ........................................................................251 33.7BOD Threshold characteristics ............................................................................253
34 Register Summary ............................................................................... 254 35 Instruction Set Summary ..................................................................... 258
vi
ATmega16HVB/32HVB
8042A-AVR-07/09
ATmega16HVB/32HVB
36 Ordering Information ........................................................................... 261
36.1ATmega16HVB ....................................................................................................261 36.2ATmega32HVB ....................................................................................................262
37 Packaging Information ........................................................................ 263
37.144X1 ....................................................................................................................263
38 Errata ..................................................................................................... 264
38.1ATmega16HVB ....................................................................................................264 38.2ATmega32HVB ....................................................................................................264
39 Revision history ................................................................................... 265
39.1Rev.D - 05/09 ......................................................................................................265 39.2Rev.C - 03/09 ......................................................................................................265 39.3Rev.B - 01/09 .......................................................................................................266 39.4Rev.A - 11/08 .......................................................................................................267
Table of Contents....................................................................................... i
vii
8042A-AVR-07/09
Table of Contentsi
Headquarters
Atmel Corporation 2325 Orchard Parkway San Jose, CA 95131 USA Tel: 1(408) 441-0311 Fax: 1(408) 487-2600
International
Atmel Asia Unit 1-5 & 16, 19/F BEA Tower, Millennium City 5 418 Kwun Tong Road Kwun Tong, Kowloon Hong Kong Tel: (852) 2245-6100 Fax: (852) 2722-1369 Atmel Europe Le Krebs 8, Rue Jean-Pierre Timbaud BP 309 78054 Saint-Quentin-enYvelines Cedex France Tel: (33) 1-30-60-70-00 Fax: (33) 1-30-60-71-11 Atmel Japan 9F, Tonetsu Shinkawa Bldg. 1-24-8 Shinkawa Chuo-ku, Tokyo 104-0033 Japan Tel: (81) 3-3523-3551 Fax: (81) 3-3523-7581
Product Contact
Web Site www.atmel.com Technical Support avr@atmel.com Sales Contact www.atmel.com/contacts
Literature Requests www.atmel.com/literature
Disclaimer: The information in this document is provided in connection with Atmel products. No license, express or implied, by estoppel or otherwise, to any intellectual property right is granted by this document or in connection with the sale of Atmel products. EXCEPT AS SET FORTH IN ATMEL'S TERMS AND CONDITIONS OF SALE LOCATED ON ATMEL'S WEB SITE, ATMEL ASSUMES NO LIABILITY WHATSOEVER AND DISCLAIMS ANY EXPRESS, IMPLIED OR STATUTORY WARRANTY RELATING TO ITS PRODUCTS INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. IN NO EVENT SHALL ATMEL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE, SPECIAL OR INCIDENTAL DAMAGES (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF PROFITS, BUSINESS INTERRUPTION, OR LOSS OF INFORMATION) ARISING OUT OF THE USE OR INABILITY TO USE THIS DOCUMENT, EVEN IF ATMEL HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. Atmel makes no representations or warranties with respect to the accuracy or completeness of the contents of this document and reserves the right to make changes to specifications and product descriptions at any time without notice. Atmel does not make any commitment to update the information contained herein. Unless specifically provided otherwise, Atmel products are not suitable for, and shall not be used in, automotive applications. Atmel's products are not intended, authorized, or warranted for use as components in applications intended to support or sustain life.
(c) 2009 Atmel Corporation. All rights reserved. Atmel(R), Atmel logo and combinations thereof, AVR(R) and others are registered trademarks or trademarks of Atmel Corporation or its subsidiaries. Other terms and product names may be trademarks of others.
8042A-AVR-07/09


▲Up To Search▲   

 
Price & Availability of ATMEGA16HVB-8X3

All Rights Reserved © IC-ON-LINE 2003 - 2022  

[Add Bookmark] [Contact Us] [Link exchange] [Privacy policy]
Mirror Sites :  [www.datasheet.hk]   [www.maxim4u.com]  [www.ic-on-line.cn] [www.ic-on-line.com] [www.ic-on-line.net] [www.alldatasheet.com.cn] [www.gdcy.com]  [www.gdcy.net]


 . . . . .
  We use cookies to deliver the best possible web experience and assist with our advertising efforts. By continuing to use this site, you consent to the use of cookies. For more information on cookies, please take a look at our Privacy Policy. X